ezu-translate 0.9.0

Translate map-engine styles (MapLibre GL, …) into ezu recipes — node-DAG Documents rendered on the CPU
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//! `symbol` layer → one label layer (`text-labels` + `text-draw`) carrying
//! the `layout.text-field` label and the `layout.icon-image` sprite. Text
//! follows `symbol-placement` (points, or along polylines for `line` /
//! `line-center`); the icon is point-placed only.
//!
//! Every converted *visible* label layer feeds the recipe's one
//! `label-placement` node, so a symbol's icon and text place as a unit
//! against the same index every other layer collides with, as in MapLibre.
//! A line-placed layer's `icon-image` has no ezu counterpart and falls back
//! to a collision-free `stamp`.

use std::collections::HashMap;

use serde_json::{Map, Value};

use crate::maplibre::filter;
use crate::maplibre::layers::fill::{resolve_number, resolve_paint_color};
use crate::maplibre::layers::paint_of;
use crate::maplibre::sources::{features_node, resolve_layer_source, Sources};
use crate::maplibre::{Report, ZoomRange};

/// MapLibre's default `text-font` stack, used when a layer omits it.
const DEFAULT_TEXT_FONT: [&str; 2] = ["Open Sans Regular", "Arial Unicode MS Regular"];

/// A `symbol` layer: place the `icon-image` sprite (`features` → `icon`
/// → `stamp`) and/or the `text-field` label (`features` → `text`) at
/// each point feature. A `text-font` entry mapped to a font URL via
/// [`ConvertOptions::fonts`](crate::maplibre::ConvertOptions) becomes a
/// `font` source; a stack with no mapping falls back to the style's
/// top-level `glyphs` endpoint (`glyphs_url`) as an SDF `glyphs` source
/// — zero configuration. No mapping and no `glyphs` skips the text
/// with a warning.
///
/// `label_layers` is the recipe's shared placement roster: `None` keeps this
/// layer's labels out of it (a `visibility: none` layer contributes no
/// collision candidates, as in MapLibre), and its text becomes a
/// self-placing `text` node instead of the `text-labels`/`text-draw` pair.
#[allow(clippy::too_many_arguments)]
pub(crate) fn convert_symbol(
    id: &str,
    layer: &Map<String, Value>,
    nodes: &mut Map<String, Value>,
    outputs: &mut Vec<String>,
    label_layers: Option<&mut Vec<String>>,
    zoom_range: ZoomRange,
    sources: &Sources,
    source_defs: &mut Map<String, Value>,
    fonts: &HashMap<String, String>,
    glyphs_url: Option<&str>,
    report: &mut Report,
) {
    let Some((source, source_layer)) = resolve_layer_source(id, layer, sources, report) else {
        return;
    };
    let (min_zoom, max_zoom) = zoom_range;
    let layout = layer.get("layout").and_then(Value::as_object);
    let icon_image = layout.and_then(|l| l.get("icon-image"));
    let has_text = layout
        .and_then(|l| l.get("text-field"))
        .is_some_and(|v| !v.is_null());

    if icon_image.is_none() && !has_text {
        report.warn(format!(
            "layer `{id}`: `symbol` without `icon-image` or `text-field` — skipped"
        ));
        return;
    }

    let base_filter_expr = filter::layer_filter_expr(layer, report, id);
    // Shared by the icon and text nodes; created on first use.
    let feat_id = format!("{id}__feat");
    let mut feat_emitted = false;
    let mut ensure_feat = |nodes: &mut Map<String, Value>| {
        if !feat_emitted {
            nodes.insert(
                feat_id.clone(),
                features_node(
                    &source,
                    &source_layer,
                    base_filter_expr.clone(),
                    min_zoom,
                    max_zoom,
                ),
            );
            feat_emitted = true;
        }
        format!("@{feat_id}")
    };

    // `symbol-placement` decides where both halves go. Point placement puts
    // the icon on the label pipeline, so it collides with everything else;
    // a line-placed icon has no such counterpart and keeps the plain stamp.
    let placement = resolve_placement(layout, id, report);
    let icon_fields = icon_image
        .filter(|_| placement == "point")
        .and_then(|v| icon_fields(id, v, layer, layout, sources, report));
    if let (Some(icon_image), None) = (icon_image, &icon_fields) {
        convert_icon_stamp(
            id,
            icon_image,
            layer,
            layout,
            nodes,
            outputs,
            sources,
            &mut ensure_feat,
            report,
        );
    }
    if has_text {
        convert_text(
            id,
            layer,
            layout,
            placement,
            icon_fields,
            zoom_range,
            nodes,
            outputs,
            label_layers,
            source_defs,
            fonts,
            glyphs_url,
            &source,
            &source_layer,
            base_filter_expr.clone(),
            &mut ensure_feat,
            report,
        );
    } else if let Some(icon_fields) = icon_fields {
        convert_icon_only(
            id,
            icon_fields,
            zoom_range,
            nodes,
            outputs,
            label_layers,
            &source,
            &source_layer,
            base_filter_expr.clone(),
            &mut ensure_feat,
        );
    }
}

/// MapLibre `symbol-placement`: `point` labels each point feature; `line` /
/// `line-center` walk the layer's polylines. Anything else falls back to
/// point with a warning.
fn resolve_placement(
    layout: Option<&Map<String, Value>>,
    id: &str,
    report: &mut Report,
) -> &'static str {
    match layout
        .and_then(|l| l.get("symbol-placement"))
        .and_then(Value::as_str)
    {
        None | Some("point") => "point",
        Some("line") => "line",
        Some("line-center") => "line-center",
        Some(other) => {
            report.warn(format!(
                "layer `{id}`: unknown `symbol-placement: {other}` — using point placement"
            ));
            "point"
        }
    }
}

/// The `icon-*` fields a point-placed `icon-image` contributes to its
/// layer's label node, or `None` when the style declares no sprite to crop
/// from (warned).
fn icon_fields(
    id: &str,
    icon_image: &Value,
    layer: &Map<String, Value>,
    layout: Option<&Map<String, Value>>,
    sources: &Sources,
    report: &mut Report,
) -> Option<Map<String, Value>> {
    let get = |key: &str| layout.and_then(|l| l.get(key));
    let mut f = Map::new();
    // A constant `icon-image` names one icon of one sheet; a data-driven one
    // is evaluated per feature against the default sheet, which can crop any
    // icon it contains.
    match icon_image.as_str() {
        Some(icon_name) => {
            let (sprite_src, sprite_icon) = sources.resolve_icon(icon_name).or_else(|| {
                report.warn(format!(
                    "layer `{id}`: icon `{icon_name}` needs a `sprite`, but the style declares none — skipped"
                ));
                None
            })?;
            f.insert("icon-sprite".into(), Value::from(format!("@{sprite_src}")));
            f.insert("icon-name".into(), Value::from(sprite_icon));
        }
        None => {
            let sprite_src = sources.default_sprite().or_else(|| {
                report.warn(format!(
                    "layer `{id}`: data-driven `icon-image` needs a `sprite`, but the style declares none — skipped"
                ));
                None
            })?;
            f.insert("icon-sprite".into(), Value::from(format!("@{sprite_src}")));
            f.insert("icon-name-expr".into(), icon_image.clone());
        }
    }

    // Constant → plain field, expression → `*-expr`.
    for (field, expr_field, value) in [
        ("icon-size", "icon-size-expr", get("icon-size")),
        (
            "icon-rotate-deg",
            "icon-rotate-deg-expr",
            get("icon-rotate"),
        ),
        ("icon-padding-px", "icon-padding-expr", get("icon-padding")),
        (
            "icon-opacity",
            "icon-opacity-expr",
            paint_of(layer).get("icon-opacity"),
        ),
    ] {
        let (constant, expr) = resolve_number(value);
        if let Some(c) = constant {
            f.insert(field.into(), Value::from(c));
        }
        if let Some(e) = expr {
            f.insert(expr_field.into(), e);
        }
    }
    if let Some(anchor) = const_string(get("icon-anchor"), "icon-anchor", id, report) {
        f.insert("icon-anchor".into(), Value::from(anchor));
    }
    if let Some(offset) = const_offset(get("icon-offset"), id, report) {
        f.insert("icon-offset".into(), serde_json::json!(offset));
    }

    // `icon-allow-overlap` (bool), superseded by the newer `icon-overlap`
    // enum, exactly as the text pair works.
    let mut allow_overlap = get("icon-allow-overlap").and_then(Value::as_bool);
    match get("icon-overlap").and_then(Value::as_str) {
        Some("always") => allow_overlap = Some(true),
        Some("never") => allow_overlap = Some(false),
        Some("cooperative") => {
            report.warn(format!(
                "layer `{id}`: `icon-overlap: cooperative` has no ezu equivalent — treated as `never`"
            ));
            allow_overlap = Some(false);
        }
        Some(other) => report.warn(format!(
            "layer `{id}`: unknown `icon-overlap: {other}` — using collision default"
        )),
        None => {}
    }
    if allow_overlap == Some(true) {
        f.insert("icon-allow-overlap".into(), Value::from(true));
    }
    if get("icon-ignore-placement").and_then(Value::as_bool) == Some(true) {
        f.insert("icon-ignore-placement".into(), Value::from(true));
    }
    if get("icon-optional").and_then(Value::as_bool) == Some(true) {
        f.insert("icon-optional".into(), Value::from(true));
    }
    if let Some(fit) = const_string(get("icon-text-fit"), "icon-text-fit", id, report) {
        f.insert("icon-text-fit".into(), Value::from(fit));
    }
    match get("icon-text-fit-padding") {
        Some(Value::Array(a)) if a.len() == 4 && a.iter().all(Value::is_number) => {
            f.insert("icon-text-fit-padding".into(), Value::Array(a.clone()));
        }
        Some(_) => report.warn(format!(
            "layer `{id}`: expression `icon-text-fit-padding` not supported — using the default"
        )),
        None => {}
    }
    Some(f)
}

/// A symbol layer with an `icon-image` but no `text-field`: the icon still
/// goes through the shared placement, as a label with no text.
#[allow(clippy::too_many_arguments)]
fn convert_icon_only(
    id: &str,
    icon_fields: Map<String, Value>,
    zoom_range: ZoomRange,
    nodes: &mut Map<String, Value>,
    outputs: &mut Vec<String>,
    label_layers: Option<&mut Vec<String>>,
    source: &str,
    source_layer: &str,
    base_filter_expr: Option<Value>,
    ensure_feat: &mut impl FnMut(&mut Map<String, Value>) -> String,
) {
    let feat_ref = ensure_feat(nodes);
    let mut spec = serde_json::json!({ "op": "text", "features": feat_ref });
    for (k, v) in icon_fields {
        spec[k] = v;
    }
    set_placement_context(
        &mut spec,
        source,
        source_layer,
        zoom_range,
        base_filter_expr,
    );
    emit_label_nodes(id, spec, nodes, outputs, label_layers);
}

/// Thread the origin source/layer, the style layer's zoom band and its
/// filter onto a label spec: the node gathers neighbour candidates straight
/// from the source, so it has to reproduce the `features` node's gates.
fn set_placement_context(
    spec: &mut Value,
    source: &str,
    source_layer: &str,
    zoom_range: ZoomRange,
    base_filter_expr: Option<Value>,
) {
    spec["source"] = Value::from(source);
    spec["layer"] = Value::from(source_layer);
    let (min_zoom, max_zoom) = zoom_range;
    if let Some(z) = min_zoom {
        spec["min-zoom"] = Value::from(z);
    }
    if let Some(z) = max_zoom {
        spec["max-zoom"] = Value::from(z);
    }
    if let Some(f) = base_filter_expr {
        spec["filter-expr"] = f;
    }
}

/// Emit a label spec as the recipe's shared pair — a `text-labels` node
/// registered in `label_layers` plus the `text-draw` that paints its winners
/// — or, for a layer kept out of the shared index, as one self-placing
/// `text` node the caller gates off.
fn emit_label_nodes(
    id: &str,
    mut spec: Value,
    nodes: &mut Map<String, Value>,
    outputs: &mut Vec<String>,
    label_layers: Option<&mut Vec<String>>,
) {
    let text_id = format!("{id}__text");
    let Some(label_layers) = label_layers else {
        spec["op"] = Value::from("text");
        nodes.insert(text_id.clone(), spec);
        outputs.push(text_id);
        return;
    };
    let labels_id = format!("{id}__labels");
    spec["op"] = Value::from("text-labels");
    nodes.insert(labels_id.clone(), spec);
    label_layers.push(labels_id.clone());
    nodes.insert(
        text_id.clone(),
        serde_json::json!({
            "op": "text-draw",
            "labels": format!("@{labels_id}"),
            "placement": format!("@{LABEL_PLACEMENT_ID}"),
        }),
    );
    outputs.push(text_id);
}

/// The fallback icon half for a line-placed layer (or one whose sprite the
/// label node can't take): `layout.icon-image` → `icon` (sprite crop) +
/// `stamp`, placed at every point without collision.
#[allow(clippy::too_many_arguments)]
fn convert_icon_stamp(
    id: &str,
    icon_image: &Value,
    layer: &Map<String, Value>,
    layout: Option<&Map<String, Value>>,
    nodes: &mut Map<String, Value>,
    outputs: &mut Vec<String>,
    sources: &Sources,
    ensure_feat: &mut impl FnMut(&mut Map<String, Value>) -> String,
    report: &mut Report,
) {
    let feat_ref = ensure_feat(nodes);
    let stamp_id = format!("{id}__stamp");
    // A constant `icon-image` crops one named icon up front (`icon` node →
    // `stamp` image). A data-driven one is passed to `stamp` as a `name-expr`
    // over the sheet's atlas, cropping each feature's icon at eval time — no
    // per-icon enumeration, since any icon in the bound sheet is croppable.
    let mut spec = match icon_image.as_str() {
        Some(icon_name) => {
            let Some((sprite_src, sprite_icon)) = sources.resolve_icon(icon_name) else {
                report.warn(format!(
                    "layer `{id}`: icon `{icon_name}` needs a `sprite`, but the style declares none — skipped"
                ));
                return;
            };
            let icon_id = format!("{id}__icon");
            nodes.insert(
                icon_id.clone(),
                serde_json::json!({ "op": "icon", "sprite": format!("@{sprite_src}"), "name": sprite_icon }),
            );
            serde_json::json!({ "op": "stamp", "features": feat_ref, "image": format!("@{icon_id}") })
        }
        None => {
            let Some(sprite_src) = sources.default_sprite() else {
                report.warn(format!(
                    "layer `{id}`: data-driven `icon-image` needs a `sprite`, but the style declares none — skipped"
                ));
                return;
            };
            serde_json::json!({
                "op": "stamp", "features": feat_ref,
                "sprite": format!("@{sprite_src}"), "name-expr": icon_image.clone()
            })
        }
    };

    // `layout.icon-size` → `scale` (constant) or `scale-expr`.
    let (size, size_expr) = resolve_number(layout.and_then(|l| l.get("icon-size")));
    if let Some(s) = size {
        if s != 1.0 {
            spec["scale"] = Value::from(s);
        }
    }
    if let Some(e) = size_expr {
        spec["scale-expr"] = e;
    }

    // `layout.icon-rotate` → `rotation-deg` (constant) or `rotation-deg-expr`.
    let (rotate, rotate_expr) = resolve_number(layout.and_then(|l| l.get("icon-rotate")));
    if let Some(r) = rotate {
        if r != 0.0 {
            spec["rotation-deg"] = Value::from(r);
        }
    }
    if let Some(e) = rotate_expr {
        spec["rotation-deg-expr"] = e;
    }

    // `paint.icon-opacity` → `opacity` (constant) or `opacity-expr`.
    let (opacity, opacity_expr) = resolve_number(paint_of(layer).get("icon-opacity"));
    if let Some(a) = opacity {
        spec["opacity"] = Value::from(a);
    }
    if let Some(e) = opacity_expr {
        spec["opacity-expr"] = e;
    }

    // A line-placed icon repeats along the path in MapLibre and is stamped at
    // the raw feature points here, outside the collision index.
    for prop in [
        "icon-allow-overlap",
        "icon-ignore-placement",
        "icon-overlap",
    ] {
        if layout.and_then(|l| l.get(prop)).is_some() {
            report.warn(format!(
                "layer `{id}`: `{prop}` not supported on a line-placed icon — stamped without collision"
            ));
        }
    }

    nodes.insert(stamp_id.clone(), spec);
    outputs.push(stamp_id);
}

/// The text half: `layout.text-field` (+ text paint/layout properties) →
/// a `text-labels` node (this layer's placement candidates, registered in
/// `label_layers`) plus the `text-draw` node that paints its winners.
#[allow(clippy::too_many_arguments)]
fn convert_text(
    id: &str,
    layer: &Map<String, Value>,
    layout: Option<&Map<String, Value>>,
    placement: &str,
    icon_fields: Option<Map<String, Value>>,
    zoom_range: ZoomRange,
    nodes: &mut Map<String, Value>,
    outputs: &mut Vec<String>,
    label_layers: Option<&mut Vec<String>>,
    source_defs: &mut Map<String, Value>,
    fonts: &HashMap<String, String>,
    glyphs_url: Option<&str>,
    source: &str,
    source_layer: &str,
    base_filter_expr: Option<Value>,
    ensure_feat: &mut impl FnMut(&mut Map<String, Value>) -> String,
    report: &mut Report,
) {
    let get = |key: &str| layout.and_then(|l| l.get(key));

    // `text-font`: a static string array (or absent → default) lowers to a
    // single stack. A data-driven expression / legacy function (A) is
    // enumerated for the literal stacks it can yield; each is lowered and
    // registered under its canonical key in `font-stacks`, the raw expression
    // is emitted as `font-expr`, and the first stack becomes the required
    // default `font`. Unenumerable expressions fall back to the default stack
    // (renders more of the map than the old "skip whole layer").
    let text_font = get("text-font");
    // A static stack is a literal font-name array; an expression (even one
    // that is syntactically an all-string array, e.g. `["get", "x"]`) is
    // data-driven. `is_expression` is a head check against the operator set,
    // matching how MapLibre itself disambiguates the two. A legacy function
    // object also takes the data-driven path (its stacks come from `stops`).
    let is_static_stack = match text_font {
        None => true,
        Some(v @ Value::Array(_)) => !maplibre_expr::is_expression(v),
        _ => false,
    };
    let mut font_expr_value: Option<Value> = None;
    let mut font_stacks_obj = Map::new();
    let font_refs: Vec<String> = if is_static_stack {
        let stack: Vec<String> = match text_font {
            Some(Value::Array(a)) => a
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect(),
            _ => DEFAULT_TEXT_FONT.iter().map(|s| s.to_string()).collect(),
        };
        match lower_stack(&stack, source_defs, fonts, glyphs_url, id, report) {
            Some(refs) => refs,
            None => return,
        }
    } else {
        let value = text_font.expect("non-static text-font is present");
        let stacks = collect_font_stacks(value);
        if stacks.is_empty() {
            report.warn(format!(
                "layer `{id}`: data-driven `text-font`: no literal stacks found — using the default stack"
            ));
            let stack: Vec<String> = DEFAULT_TEXT_FONT.iter().map(|s| s.to_string()).collect();
            match lower_stack(&stack, source_defs, fonts, glyphs_url, id, report) {
                Some(refs) => refs,
                None => return,
            }
        } else {
            // Lower every enumerated stack; the first that lowers is the
            // default `font`, all that lower populate the registry.
            let mut default_refs: Option<Vec<String>> = None;
            for stack in &stacks {
                let Some(refs) = lower_stack(stack, source_defs, fonts, glyphs_url, id, report)
                else {
                    continue;
                };
                if default_refs.is_none() {
                    default_refs = Some(refs.clone());
                }
                let key = stack.iter().map(|s| s.trim()).collect::<Vec<_>>().join(",");
                font_stacks_obj.entry(key).or_insert_with(|| {
                    Value::Array(refs.iter().cloned().map(Value::from).collect())
                });
            }
            match default_refs {
                Some(refs) => {
                    font_expr_value = Some(value.clone());
                    refs
                }
                // No stack lowered (no `--font` mapping and no `glyphs`
                // endpoint) — `lower_stack` already warned per stack.
                None => return,
            }
        }
    };
    let font_value = Value::Array(font_refs.into_iter().map(Value::from).collect());

    // `text-field`: a constant may carry `{token}`s (rewritten to a
    // `concat`-of-`get` expression); expressions / legacy functions pass
    // through raw. A `format` expression passes through too: the `text` node
    // renders its sections natively (font / scale / colour / vertical-align),
    // so we only register each section's `text-font` in the stack registry.
    let text_value = match get("text-field") {
        Some(Value::String(s)) => match rewrite_field_tokens(s) {
            Some(expr) => expr,
            None => Value::String(s.clone()),
        },
        Some(v @ Value::Array(_)) => {
            register_format_section_fonts(
                v,
                &mut font_stacks_obj,
                source_defs,
                fonts,
                glyphs_url,
                id,
            );
            v.clone()
        }
        // Legacy `{stops}` function: its output strings may carry
        // `{token}`s that the raw passthrough would render literally.
        Some(v @ Value::Object(_)) => match rewrite_legacy_stops_tokens(v) {
            Some(expr) => expr,
            None => v.clone(),
        },
        _ => return,
    };

    let feat_ref = ensure_feat(nodes);
    let mut spec = serde_json::json!({
        "op": "text", "features": feat_ref,
        "font": font_value, "text": text_value
    });
    // The raw data-driven `text-font` expression, if any …
    if let Some(expr) = font_expr_value {
        spec["font-expr"] = expr;
    }
    // … and the stack registry: enumerated `font-expr` stacks and/or `format`
    // section `text-font`s. Emitted whenever non-empty (a `format` label can
    // need it without a `font-expr`).
    if !font_stacks_obj.is_empty() {
        spec["font-stacks"] = Value::Object(font_stacks_obj);
    }

    // Paint / size: constant → plain field, expression → `*-expr`.
    let paint = paint_of(layer);
    let (size, size_expr) = resolve_number(get("text-size"));
    if let Some(s) = size {
        spec["size"] = Value::from(s);
    }
    if let Some(e) = size_expr {
        spec["size-expr"] = e;
    }
    let (color, color_expr) = resolve_paint_color(paint.get("text-color"));
    if let Some(c) = color {
        spec["color"] = Value::from(c);
    }
    if let Some(e) = color_expr {
        spec["color-expr"] = e;
    }
    let (halo_color, halo_color_expr) = resolve_paint_color(paint.get("text-halo-color"));
    if let Some(c) = halo_color {
        spec["halo-color"] = Value::from(c);
    }
    if let Some(e) = halo_color_expr {
        spec["halo-color-expr"] = e;
    }
    let (halo_width, halo_width_expr) = resolve_number(paint.get("text-halo-width"));
    if let Some(w) = halo_width {
        spec["halo-width"] = Value::from(w);
    }
    if let Some(e) = halo_width_expr {
        spec["halo-width-expr"] = e;
    }
    let (opacity, opacity_expr) = resolve_number(paint.get("text-opacity"));
    if let Some(a) = opacity {
        spec["opacity"] = Value::from(a);
    }
    if let Some(e) = opacity_expr {
        spec["opacity-expr"] = e;
    }

    // Layout constants. The `text` node takes these at build time, so an
    // expression here falls back to the default with a warning.
    if let Some(anchor) = const_string(get("text-anchor"), "text-anchor", id, report) {
        spec["anchor"] = Value::from(anchor);
    }
    // `text-variable-anchor`: an ordered list of anchors the renderer tries on
    // collision. Emitted as `anchor-variants`, which overrides `anchor`.
    if let Some(variants) = const_anchor_list(get("text-variable-anchor"), id, report) {
        spec["anchor-variants"] = serde_json::json!(variants);
        // `text-radial-offset` pairs with variable anchors: the em distance
        // each anchor pushes the label away from the point.
        if let Some(r) = const_number(get("text-radial-offset"), "text-radial-offset", id, report) {
            spec["radial-offset"] = Value::from(r);
        }
    }
    if let Some(justify) = const_string(get("text-justify"), "text-justify", id, report) {
        spec["justify"] = Value::from(justify);
    }
    if let Some(transform) = const_string(get("text-transform"), "text-transform", id, report) {
        spec["transform"] = Value::from(transform);
    }
    if let Some(offset) = const_offset(get("text-offset"), id, report) {
        spec["offset-em"] = serde_json::json!(offset);
    }
    if let Some(w) = const_number(get("text-max-width"), "text-max-width", id, report) {
        spec["max-width-em"] = Value::from(w);
    }
    if let Some(h) = const_number(get("text-line-height"), "text-line-height", id, report) {
        spec["line-height"] = Value::from(h);
    }
    if let Some(s) = const_number(
        get("text-letter-spacing"),
        "text-letter-spacing",
        id,
        report,
    ) {
        spec["letter-spacing-em"] = Value::from(s);
    }

    // Line placement and its layout knobs (point placement is the node
    // default and ignores them).
    if placement != "point" {
        spec["placement"] = Value::from(placement);
        if let Some(s) = const_number(get("symbol-spacing"), "symbol-spacing", id, report) {
            spec["spacing-px"] = Value::from(s);
        }
        if let Some(a) = const_number(get("text-max-angle"), "text-max-angle", id, report) {
            spec["max-angle-deg"] = Value::from(a);
        }
        if get("text-keep-upright").and_then(Value::as_bool) == Some(false) {
            spec["keep-upright"] = Value::from(false);
        }
        // Glyphs always rotate with the line in ezu (map alignment); a
        // viewport-aligned line label has no static-renderer equivalent.
        if get("text-rotation-alignment").and_then(Value::as_str) == Some("viewport") {
            report.warn(format!(
                "layer `{id}`: `text-rotation-alignment: viewport` on line placement not supported — glyphs follow the line"
            ));
        }
    }

    // The `icon-image` half rides the same node, so the symbol's icon and
    // text are placed as one unit against the shared index.
    if let Some(icon_fields) = icon_fields {
        for (k, v) in icon_fields {
            spec[k] = v;
        }
    }

    // Collision (deterministic cross-tile placement). Always thread the
    // origin source/layer (+ the layer filter) through so the `text` node
    // gathers neighbour candidates and filters them exactly like its own
    // features; collision itself is on by default in the `text` node.
    set_placement_context(
        &mut spec,
        source,
        source_layer,
        zoom_range,
        base_filter_expr,
    );

    // `text-allow-overlap` (bool), superseded by the newer `text-overlap`
    // enum when present: `always` → allow, `never`/absent → collide,
    // `cooperative` → treated as `never` with a warning (no cooperative
    // fade model here).
    let mut allow_overlap = get("text-allow-overlap").and_then(Value::as_bool);
    match get("text-overlap").and_then(Value::as_str) {
        Some("always") => allow_overlap = Some(true),
        Some("never") => allow_overlap = Some(false),
        Some("cooperative") => {
            report.warn(format!(
                "layer `{id}`: `text-overlap: cooperative` has no ezu equivalent — treated as `never`"
            ));
            allow_overlap = Some(false);
        }
        Some(other) => report.warn(format!(
            "layer `{id}`: unknown `text-overlap: {other}` — using collision default"
        )),
        None => {}
    }
    if allow_overlap == Some(true) {
        spec["allow-overlap"] = Value::from(true);
    }

    if get("text-ignore-placement").and_then(Value::as_bool) == Some(true) {
        spec["ignore-placement"] = Value::from(true);
    }
    // `text-padding`: constant → `padding-px`, expression (e.g. a zoom curve)
    // → `padding-expr`, evaluated per feature.
    let (padding, padding_expr) = resolve_number(get("text-padding"));
    if let Some(p) = padding {
        spec["padding-px"] = Value::from(p);
    }
    if let Some(e) = padding_expr {
        spec["padding-expr"] = e;
    }
    // `symbol-sort-key`: constant or expression — the `text` node parses
    // either on `sort-key-expr`.
    if let Some(v) = get("symbol-sort-key") {
        spec["sort-key-expr"] = v.clone();
    }
    // `text-optional`: the icon may place where the text can't (the icon's
    // own `icon-optional` is set by `icon_fields`).
    if get("text-optional").and_then(Value::as_bool) == Some(true) {
        spec["text-optional"] = Value::from(true);
    }

    // Placement is shared by every label layer of the style, the way
    // maplibre-gl-js runs one collision index for all symbol layers: this
    // layer contributes its candidates (`text-labels`), the recipe-wide
    // `label-placement` node decides them all, and `text-draw` paints the
    // winners. `label_layers` records the contribution in style order; the
    // caller emits the placement node once every layer is known. A layer
    // kept out of it gets one self-placing `text` node instead, which the
    // caller gates off — so it neither draws nor collides.
    emit_label_nodes(id, spec, nodes, outputs, label_layers);
}

/// Node id of the recipe's shared placement node — referenced by every
/// `text-draw` node and emitted once, after the layer walk.
pub(crate) const LABEL_PLACEMENT_ID: &str = "__label_placement";

/// Emit the recipe's shared `label-placement` node over `label_layers` (in
/// style order, bottom first — the node gives the topmost layer priority).
/// Nothing to do for a style with no label layer.
pub(crate) fn emit_label_placement(nodes: &mut Map<String, Value>, label_layers: &[String]) {
    if label_layers.is_empty() {
        return;
    }
    nodes.insert(
        LABEL_PLACEMENT_ID.to_string(),
        serde_json::json!({
            "op": "label-placement",
            "labels": label_layers
                .iter()
                .map(|id| Value::from(format!("@{id}")))
                .collect::<Vec<_>>(),
        }),
    );
}

/// Reuse (by URL) or declare a `font` source for one fontstack entry.
/// Returns the source id, derived from the entry name.
/// Lower one MapLibre font stack to ezu `font`/`glyphs` source names.
/// Mapped entries (present in the `--font` table) become `font` sources; if
/// none are mapped, the whole stack becomes one `glyphs` source over
/// `glyphs_url` (its `fontstack` = names joined `", "`, MapLibre's server
/// convention). Neither available → `None` (warned). Shared by the static
/// `text-font` path and each enumerated dynamic stack.
fn lower_stack(
    stack: &[String],
    source_defs: &mut Map<String, Value>,
    fonts: &HashMap<String, String>,
    glyphs_url: Option<&str>,
    id: &str,
    report: &mut Report,
) -> Option<Vec<String>> {
    let (mapped, unmapped): (Vec<&String>, Vec<&String>) =
        stack.iter().partition(|name| fonts.contains_key(*name));
    if mapped.is_empty() {
        // Zero-config compat: serve the stack from the style's glyph
        // endpoint as SDF ranges (server-side fallback, as in MapLibre).
        let Some(glyphs_url) = glyphs_url else {
            report.warn(format!(
                "layer `{id}`: `symbol` text: no font mapping for {stack:?} and the style has no `glyphs` endpoint — pass `--font \"NAME=URL\"`; text skipped"
            ));
            return None;
        };
        Some(vec![ensure_glyphs_source(
            source_defs,
            glyphs_url,
            &stack.join(", "),
        )])
    } else {
        // An explicit mapping wins over the `glyphs` endpoint.
        if !unmapped.is_empty() {
            report.warn(format!(
                "layer `{id}`: `symbol` text: no font mapping for {unmapped:?} — using the mapped subset"
            ));
        }
        Some(
            mapped
                .iter()
                .map(|name| {
                    let url = fonts
                        .get(name.as_str())
                        .expect("partitioned on containment");
                    ensure_font_source(source_defs, name, url)
                })
                .collect(),
        )
    }
}

/// A JSON array all of whose elements are strings → the owned name list.
fn as_string_array(v: &Value) -> Option<Vec<String>> {
    let a = v.as_array()?;
    let mut names = Vec::with_capacity(a.len());
    for x in a {
        names.push(x.as_str()?.to_string());
    }
    Some(names)
}

/// Enumerate the literal font stacks a data-driven `text-font` value can
/// yield, in document order, deduped: every `["literal", [<strings>]]` in the
/// expression tree, plus a legacy function's `stops` outputs and `default`
/// (both string arrays). MapLibre likewise requires data-driven `text-font`
/// outputs to be literals, so a syntactic scan is faithful; anything it misses
/// falls back to the default stack at eval.
fn collect_font_stacks(v: &Value) -> Vec<Vec<String>> {
    fn push_unique(out: &mut Vec<Vec<String>>, names: Vec<String>) {
        if !names.is_empty() && !out.contains(&names) {
            out.push(names);
        }
    }
    fn rec(v: &Value, out: &mut Vec<Vec<String>>) {
        match v {
            Value::Array(a) => {
                // `["literal", <data>]` — the operand is data, not a
                // sub-expression: collect a string array, never recurse in.
                if a.len() == 2 && a[0].as_str() == Some("literal") {
                    if let Some(names) = as_string_array(&a[1]) {
                        push_unique(out, names);
                    }
                    return;
                }
                for x in a {
                    rec(x, out);
                }
            }
            Value::Object(m) => {
                // Legacy `{stops}` function: each stop is `[input, output]`.
                if let Some(Value::Array(stops)) = m.get("stops") {
                    for stop in stops {
                        if let Some(output) = stop.as_array().and_then(|p| p.get(1)) {
                            if let Some(names) = as_string_array(output) {
                                push_unique(out, names);
                            }
                        }
                    }
                }
                if let Some(names) = m.get("default").and_then(as_string_array) {
                    push_unique(out, names);
                }
                for val in m.values() {
                    rec(val, out);
                }
            }
            _ => {}
        }
    }
    let mut out = Vec::new();
    rec(v, &mut out);
    out
}

/// Walk a `text-field` value and register every `format` section's `text-font`
/// in `font_stacks` (keyed by its canonical `,`-joined name, resolved through
/// [`lower_stack`]). Descends the whole tree, so `format`s nested in `case` /
/// `match` (as the Protomaps multi-script labels use) are found too.
///
/// Section-font lowering is best-effort and quiet: a stack that can't be
/// mapped is simply not registered (the `text` node falls back to the layer's
/// default stack for that section), so `lower_stack`'s warnings are discarded
/// rather than spamming one "text skipped" per unmapped section — the label's
/// text is not skipped.
fn register_format_section_fonts(
    v: &Value,
    font_stacks: &mut Map<String, Value>,
    source_defs: &mut Map<String, Value>,
    fonts: &HashMap<String, String>,
    glyphs_url: Option<&str>,
    id: &str,
) {
    match v {
        Value::Array(arr) => {
            if arr.first().and_then(Value::as_str) == Some("format") {
                // `["format", content0, style0, content1, style1, …]` — style
                // objects sit at the even indices from 2.
                let mut i = 2;
                while i < arr.len() {
                    if let Some(obj) = arr[i].as_object() {
                        if let Some(tf) = obj.get("text-font") {
                            // A section `text-font` is a literal stack (bare
                            // array or `["literal", […]]`) or a small
                            // expression; enumerate its stacks like the layer's.
                            let stacks = match as_string_array(tf) {
                                Some(s) => vec![s],
                                None => collect_font_stacks(tf),
                            };
                            let mut quiet = Report::default();
                            for stack in &stacks {
                                if let Some(refs) = lower_stack(
                                    stack,
                                    source_defs,
                                    fonts,
                                    glyphs_url,
                                    id,
                                    &mut quiet,
                                ) {
                                    let key = stack
                                        .iter()
                                        .map(|s| s.trim())
                                        .collect::<Vec<_>>()
                                        .join(",");
                                    font_stacks.entry(key).or_insert_with(|| {
                                        Value::Array(
                                            refs.iter().cloned().map(Value::from).collect(),
                                        )
                                    });
                                }
                            }
                        }
                    }
                    i += 2;
                }
            }
            for x in arr {
                register_format_section_fonts(x, font_stacks, source_defs, fonts, glyphs_url, id);
            }
        }
        Value::Object(m) => {
            for val in m.values() {
                register_format_section_fonts(val, font_stacks, source_defs, fonts, glyphs_url, id);
            }
        }
        _ => {}
    }
}

fn ensure_font_source(source_defs: &mut Map<String, Value>, name: &str, url: &str) -> String {
    // One source per distinct URL, shared across layers and stacks.
    if let Some((id, _)) = source_defs
        .iter()
        .find(|(_, d)| d["type"] == "font" && d["url"] == url)
    {
        return id.clone();
    }
    let id = unique_source_id(source_defs, &kebab_id(name));
    source_defs.insert(
        id.clone(),
        serde_json::json!({ "type": "font", "url": url }),
    );
    id
}

/// Reuse or declare a `glyphs` source for one fontstack string served
/// from the style's glyph endpoint. Returns the source id, derived
/// from the joined stack.
fn ensure_glyphs_source(
    source_defs: &mut Map<String, Value>,
    url: &str,
    fontstack: &str,
) -> String {
    // One source per distinct (endpoint, fontstack), shared across layers.
    if let Some((id, _)) = source_defs
        .iter()
        .find(|(_, d)| d["type"] == "glyphs" && d["url"] == url && d["fontstack"] == fontstack)
    {
        return id.clone();
    }
    let id = unique_source_id(source_defs, &kebab_id(fontstack));
    source_defs.insert(
        id.clone(),
        serde_json::json!({ "type": "glyphs", "url": url, "fontstack": fontstack }),
    );
    id
}

/// `"Noto Sans Regular"` → `"noto-sans-regular"` (source-id shape).
fn kebab_id(name: &str) -> String {
    let mut base: String = name
        .to_lowercase()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
    while base.contains("--") {
        base = base.replace("--", "-");
    }
    base.trim_matches('-').to_string()
}

/// `base`, suffixed on collision with an unrelated source name.
fn unique_source_id(source_defs: &Map<String, Value>, base: &str) -> String {
    let mut id = base.to_string();
    let mut n = 2;
    while source_defs.contains_key(&id) {
        id = format!("{base}-{n}");
        n += 1;
    }
    id
}

/// Rewrite a constant `text-field` carrying `{token}`s into a MapLibre
/// expression: `{name}` → `["to-string", ["get", "name"]]`, mixed text →
/// `["concat", …]`. Returns `None` when the string has no tokens.
fn rewrite_field_tokens(s: &str) -> Option<Value> {
    let mut parts: Vec<Value> = Vec::new();
    let mut literal = String::new();
    let mut rest = s;
    let mut found = false;
    while let Some(open) = rest.find('{') {
        let after = &rest[open + 1..];
        let Some(close) = after.find('}') else {
            break; // unclosed brace: literal from here on
        };
        let token = &after[..close];
        literal.push_str(&rest[..open]);
        if !literal.is_empty() {
            parts.push(Value::String(std::mem::take(&mut literal)));
        }
        parts.push(serde_json::json!(["to-string", ["get", token]]));
        found = true;
        rest = &after[close + 1..];
    }
    if !found {
        return None;
    }
    literal.push_str(rest);
    if !literal.is_empty() {
        parts.push(Value::String(literal));
    }
    if parts.len() == 1 {
        return Some(parts.pop().expect("one part"));
    }
    let mut concat = vec![Value::String("concat".into())];
    concat.extend(parts);
    Some(Value::Array(concat))
}

/// Rewrite a legacy zoom-interval `{stops}` `text-field` whose output
/// strings carry `{token}`s into a `["step", ["zoom"], …]` expression
/// with each output token-expanded (legacy interval semantics — the
/// first output also covers zooms below the first stop — match `step`).
/// Returns `None` when nothing needs rewriting or the function isn't a
/// plain zoom-interval string function (data-driven `property`,
/// `categorical`, non-string outputs): those pass through raw as before.
fn rewrite_legacy_stops_tokens(v: &Value) -> Option<Value> {
    let obj = v.as_object()?;
    if obj.contains_key("property") {
        return None;
    }
    match obj.get("type").and_then(Value::as_str) {
        None | Some("interval") => {}
        Some(_) => return None,
    }
    let stops = obj.get("stops")?.as_array()?;
    let mut pairs: Vec<(f64, &str)> = Vec::with_capacity(stops.len());
    for stop in stops {
        let pair = stop.as_array()?;
        pairs.push((pair.first()?.as_f64()?, pair.get(1)?.as_str()?));
    }
    if pairs.is_empty() || !pairs.iter().any(|(_, s)| s.contains('{')) {
        return None;
    }
    let expand = |s: &str| rewrite_field_tokens(s).unwrap_or_else(|| Value::String(s.into()));
    if pairs.len() == 1 {
        return Some(expand(pairs[0].1));
    }
    let mut step = vec![
        Value::String("step".into()),
        serde_json::json!(["zoom"]),
        expand(pairs[0].1),
    ];
    for (input, output) in &pairs[1..] {
        step.push(Value::from(*input));
        step.push(expand(output));
    }
    Some(Value::Array(step))
}

/// A constant string layout property; an expression warns and yields
/// `None` (the node default applies).
fn const_string(v: Option<&Value>, prop: &str, id: &str, report: &mut Report) -> Option<String> {
    match v {
        None => None,
        Some(Value::String(s)) => Some(s.clone()),
        Some(_) => {
            report.warn(format!(
                "layer `{id}`: expression `{prop}` not supported — using the default"
            ));
            None
        }
    }
}

/// A constant numeric layout property; an expression warns and yields
/// `None` (the node default applies).
fn const_number(v: Option<&Value>, prop: &str, id: &str, report: &mut Report) -> Option<f64> {
    match v {
        None => None,
        Some(n) if n.is_number() => n.as_f64(),
        Some(_) => {
            report.warn(format!(
                "layer `{id}`: expression `{prop}` not supported — using the default"
            ));
            None
        }
    }
}

/// A constant `text-variable-anchor` (an array of anchor-name strings); an
/// expression or a non-string entry warns and yields `None`. An empty array
/// yields `None` (no variants).
fn const_anchor_list(v: Option<&Value>, id: &str, report: &mut Report) -> Option<Vec<String>> {
    match v {
        None => None,
        Some(Value::Array(a)) if !a.is_empty() && a.iter().all(Value::is_string) => Some(
            a.iter()
                .filter_map(|s| s.as_str().map(str::to_string))
                .collect(),
        ),
        Some(_) => {
            report.warn(format!(
                "layer `{id}`: expression `text-variable-anchor` not supported — using `text-anchor`"
            ));
            None
        }
    }
}

/// A constant `text-offset` (`[x, y]` in em); an expression warns and
/// yields `None`.
fn const_offset(v: Option<&Value>, id: &str, report: &mut Report) -> Option<[f64; 2]> {
    match v {
        None => None,
        Some(Value::Array(a)) if a.len() == 2 && a.iter().all(Value::is_number) => {
            Some([a[0].as_f64()?, a[1].as_f64()?])
        }
        Some(_) => {
            report.warn(format!(
                "layer `{id}`: expression `text-offset` not supported — using the default"
            ));
            None
        }
    }
}