mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
use std::path::PathBuf;

use tracing::Level;

use super::util::FixtureLog;
use crate::collections::VecSet;
use crate::feature::Value;
use crate::layer::FontStack;
use crate::property::table::Kind;
use crate::style::parse::Parser;
use crate::{StyleRegistry, log_target};

fn fixtures_dir() -> PathBuf {
    std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("testdata/test/fixtures/style_parser")
}

/// The name of every `<name>.info.json` in the fixture directory.
fn fixture_names() -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(fixtures_dir())
        .unwrap()
        .filter_map(|entry| {
            let name = entry.unwrap().file_name().into_string().unwrap();
            name.strip_suffix(".info.json").map(str::to_owned)
        })
        .collect();
    names.sort();
    names
}

/// The level of a fixture's severity, as the C++ core names it.
fn fixture_level(severity: &str) -> Level {
    match severity {
        "ERROR" => Level::ERROR,
        "WARNING" => Level::WARN,
        "INFO" => Level::INFO,
        _ => panic!("unknown severity {severity}"),
    }
}

/// The target of this crate's records of a fixture's event, as the C++ core
/// names it: `ParseStyle` is `mln_style::parse_style`.
fn fixture_target(event: &str) -> String {
    let mut target = String::from("mln_style::");
    for (i, c) in event.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            target.push('_');
        }
        target.push(c.to_ascii_lowercase());
    }
    target
}

/// One `StyleParserTest.ParseStyle` instance. Returns the failure, if any.
fn parse_style_fixture(name: &str) -> Result<(), String> {
    let base = fixtures_dir().join(name);
    let log = FixtureLog::new();

    let info_doc: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(base.with_extension("info.json")).unwrap()).unwrap();
    let style_json = std::fs::read_to_string(base.with_extension("style.json")).unwrap();

    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    if let Err(error) = parser.parse(&style_json) {
        tracing::error!(target: log_target::PARSE_STYLE, error = %format_args!("Failed to parse style: {error}"), "Style is invalid");
    }

    for (property_name, value) in info_doc.as_object().unwrap() {
        if let Some(js_log) = value.get("log") {
            for js_entry in js_log.as_array().unwrap() {
                let js_entry = js_entry.as_array().unwrap();
                let count = js_entry[0].as_u64().unwrap() as usize;
                let level = fixture_level(js_entry[1].as_str().unwrap());
                let target = fixture_target(js_entry[2].as_str().unwrap());
                let msg = js_entry[3].as_str().unwrap();
                // The fixtures name the parser's error text, which the log carries as a field.
                let observed = log.count(level, &target, &fixture_line(msg)) + log.count_error(level, &target, msg);
                if count != observed {
                    return Err(format!("{name}/{property_name}: Message: {msg}: expected {count}, got {observed}"));
                }
            }
        }
        let unchecked = log.unchecked();
        if !unchecked.is_empty() {
            return Err(format!("Unchecked Log Messages ({name}/{property_name}): {unchecked:?}"));
        }
    }
    Ok(())
}

/// A fixture's message as the log renders it: the layer a text-font warning
/// names is a field.
fn fixture_line(msg: &str) -> String {
    const TAIL: &str = " has an invalid value for text-font and will not render text. Output values must be contained as literals within the expression.";
    match msg.strip_prefix("Layer '").and_then(|rest| rest.split_once('\'')) {
        Some((layer_id, tail)) if tail == TAIL => {
            format!("Layer{TAIL} layer_id={layer_id}")
        }
        _ => msg.to_owned(),
    }
}

/// Runs the style parser test over every fixture.
// gtest: StyleParserTest.ParseStyle
#[test]
fn parse_style() {
    let names = fixture_names();
    assert_ne!(names, Vec::<String>::new());
    let mut failures = Vec::new();
    for name in &names {
        if let Err(failure) = parse_style_fixture(name) {
            failures.push(failure);
        }
    }
    assert!(failures.is_empty(), "{}", failures.join("\n"));
}

// gtest: StyleParser.SpriteAsString
#[test]
fn sprite_as_string() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "sprite": "https://example.com/default/markers"
    }"#,
        )
        .unwrap();
    let result = &parser.sprites;
    assert_eq!(1, result.len());
    assert_eq!("https://example.com/default/markers", result[0].sprite_url);
    assert_eq!("default", result[0].id);
}

// gtest: StyleParser.SpriteAsArrayEmpty
#[test]
fn sprite_as_array_empty() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "sprite": []
    }"#,
        )
        .unwrap();
    assert_eq!(0, parser.sprites.len());
}

// gtest: StyleParser.SpriteAsArraySingle
#[test]
fn sprite_as_array_single() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "sprite": [{
            "id": "default",
            "url": "https://example.com/default/markers"
        }]
    }"#,
        )
        .unwrap();
    let result = &parser.sprites;
    assert_eq!(1, result.len());
    assert_eq!("https://example.com/default/markers", result[0].sprite_url);
    assert_eq!("default", result[0].id);
}

// gtest: StyleParser.SpriteAsArrayMultiple
#[test]
fn sprite_as_array_multiple() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "sprite": [{
            "id": "default",
            "url": "https://example.com/default/markers"
        },{
            "id": "hiking",
            "url": "https://example.com/hiking/markers"
        }]
    }"#,
        )
        .unwrap();
    let result = &parser.sprites;
    assert_eq!(2, result.len());
    assert_eq!("https://example.com/default/markers", result[0].sprite_url);
    assert_eq!("default", result[0].id);
    assert_eq!("https://example.com/hiking/markers", result[1].sprite_url);
    assert_eq!("hiking", result[1].id);
}

// gtest: StyleParser.FontStacks
#[test]
fn font_stacks() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    let _ = parser.parse(&std::fs::read_to_string(fixtures_dir().join("font_stacks.json")).unwrap());
    let expected: VecSet<FontStack> = [vec!["a"], vec!["a", "b"], vec!["a", "b", "c"]]
        .into_iter()
        .map(|v| v.into_iter().map(str::to_owned).collect())
        .collect();
    let result = parser.font_stacks();
    assert_eq!(expected, result);
}

fn symbol_font_stacks(layout: &str) -> VecSet<FontStack> {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    let _ = parser.parse(&format!(
        r#"{{
        "version": 8,
        "layers": [{{
            "id": "symbol",
            "type": "symbol",
            "source": "vector",
            "layout": {layout}
        }}]
    }}"#
    ));
    parser.font_stacks()
}

fn arial_helvetica() -> VecSet<FontStack> {
    [vec!["Arial".to_owned()], vec!["Helvetica".to_owned()]].into_iter().collect()
}

// gtest: StyleParser.FontStacksNoTextField
#[test]
fn font_stacks_no_text_field() {
    let result = symbol_font_stacks(r#"{"text-font": ["a"]}"#);
    assert_eq!(0, result.len());
}

// gtest: StyleParser.FontStacksCaseExpression
#[test]
fn font_stacks_case_expression() {
    let result = symbol_font_stacks(
        r#"{
                "text-field": "a",
                "text-font": ["case", ["==", "a", ["string", ["get", "text-font"]]], ["literal", ["Arial"]], ["literal", ["Helvetica"]]]
            }"#,
    );
    assert_eq!(arial_helvetica(), result);
}

// gtest: StyleParser.FontStacksMatchExpression
#[test]
fn font_stacks_match_expression() {
    let result = symbol_font_stacks(
        r#"{
                "text-field": "a",
                "text-font": ["match", ["get", "text-font"], "a", ["literal", ["Arial"]], ["literal", ["Helvetica"]]]
            }"#,
    );
    assert_eq!(arial_helvetica(), result);
}

// gtest: StyleParser.FontStacksStepExpression
#[test]
fn font_stacks_step_expression() {
    let result = symbol_font_stacks(
        r#"{
                "text-field": "a",
                "text-font": ["array", "string", ["step", ["get", "text-font"], ["literal", ["Arial"]], 0, ["literal", ["Helvetica"]]]]
            }"#,
    );
    assert_eq!(arial_helvetica(), result);
}

// gtest: StyleParser.FontStacksGetExpression
#[test]
fn font_stacks_get_expression() {
    // Invalid style, but not currently validated.
    let result = symbol_font_stacks(
        r#"{
                "text-field": "a",
                "text-font": ["array", "string", ["get", "text-font"]]
            }"#,
    );
    assert_eq!(0, result.len());
}

// gtest: StyleParser.ZoomCurve
#[test]
fn zoom_curve() {
    use crate::expression::dsl::{interpolate, linear, literal, zoom};
    use crate::expression::find_zoom_curve_checked;
    use crate::expression::value::Value;

    let zoom_interp = || {
        interpolate(linear(), zoom(), vec![(0.0, literal(Value::Number(0.0))), (0.0, literal(Value::Number(0.0)))])
            .unwrap()
    };

    let expr1 =
        interpolate(linear(), literal(Value::Number(0.0)), vec![(0.0, zoom_interp()), (0.0, zoom_interp())]).unwrap();
    assert!(find_zoom_curve_checked(&expr1).is_none());

    let expr2 = interpolate(linear(), zoom(), vec![(0.0, literal(Value::Number(0.0))), (0.0, zoom_interp())]).unwrap();
    assert!(find_zoom_curve_checked(&expr2).is_none());
}

// Port-only: C++ cuts `unicode-range` strings by bytes (`substr(2)`), also
// inside a multibyte character; the range is then invalid, not a panic.
#[test]
fn font_face_unicode_range_with_multibyte_character() {
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "font-faces": {
            "Face": [{ "url": "face.ttf", "unicode-range": ["Ué0-FF", "U+0-FF"] }]
        }
    }"#,
        )
        .unwrap();
    let faces = parser.font_faces.unwrap();
    assert_eq!(faces.len(), 1);
    assert_eq!(faces[0].ranges, vec![(0, 0xFF)]);
}

// gtest: StyleParser.FallbackFontFaces
#[test]
fn fallback_font_faces() {
    use crate::style::parse::parse_fallback_font_faces;

    let faces = parse_fallback_font_faces(
        r#"[{"url": "a.ttf", "unicode-range": ["U+1000-109F", "U+A9E0-A9FF"]}, {"url": "b.ttf"}]"#,
    )
    .unwrap();
    assert_eq!(faces.len(), 2);
    assert_eq!(faces[0].name, "");
    assert_eq!(faces[0].url, "a.ttf");
    assert_eq!(faces[0].ranges, vec![(0x1000, 0x109F), (0xA9E0, 0xA9FF)]);
    assert_eq!(faces[1].ranges, vec![(0, 0x0010_FFFF)]);

    assert!(parse_fallback_font_faces("{}").is_err());
    assert!(parse_fallback_font_faces("[1]").is_err());
    assert!(parse_fallback_font_faces(r#"[{"unicode-range": ["U+0-FF"]}]"#).is_err());
    assert!(parse_fallback_font_faces(r#"[{"url": "a.ttf", "unicode-range": ["U+XYZ-FF"]}]"#).is_err());
}

// gtest: StyleParser.NestingDepthLimit
// Port-only: serde_json admits 127 levels of nesting rather than 256, and
// words its error differently.
#[test]
fn nesting_depth_limit() {
    let parse = |depth: usize| {
        let json = format!("{}{}", "[".repeat(depth), "]".repeat(depth));
        Parser::new(&StyleRegistry::with_builtins()).parse(&json).unwrap_err().to_string()
    };

    assert_eq!(parse(127), "style must be an object");
    assert_eq!(parse(128), "recursion limit exceeded at line 1 column 128");
    // Deep enough to overflow the stack if the parser recursed through it all.
    assert!(parse(1_000_000).starts_with("recursion limit exceeded"));
}

// Port-only: the JSON depth limit is what bounds how deeply expressions and
// filters nest, so the deepest style it admits must parse on a 1 MiB stack,
// the browser build's default. "interpolate" uses the most stack per level.
#[test]
fn deepest_admitted_style_parses_on_a_1_mib_stack() {
    let nest =
        |wrap: &str, base: &str, depth: usize| (0..depth).fold(base.to_owned(), |inner, _| wrap.replace('X', &inner));
    let style = |depth: usize| {
        let filter = nest(r#"["all", X, ["==", ["get", "a"], 1]]"#, r#"["==", ["get", "a"], 1]"#, depth);
        let radius =
            nest(r#"["interpolate", ["linear"], ["get", "a"], 0, X, 1, 0]"#, r#"["number", ["get", "a"]]"#, depth);
        format!(
            r#"{{"version": 8, "sources": {{"s": {{"type": "vector", "tiles": ["http://example.com/{{z}}/{{x}}/{{y}}"]}}}},
                "layers": [{{"id": "c", "type": "circle", "source": "s", "source-layer": "l",
                             "filter": {filter}, "paint": {{"circle-radius": {radius}}}}}]}}"#
        )
    };
    let fits = |depth: usize| serde_json::from_str::<serde_json::Value>(&style(depth)).is_ok();
    let depth = (0..200).take_while(|&depth| fits(depth)).last().unwrap();
    assert!(depth >= 120, "{depth}");

    let json = style(depth);
    std::thread::Builder::new()
        .stack_size(1024 * 1024)
        .spawn(move || {
            let mut parser = Parser::new(&StyleRegistry::with_builtins());
            parser.parse(&json).unwrap();
            assert_eq!(parser.layers.len(), 1);
        })
        .unwrap()
        .join()
        .unwrap();
}

/// A layout or paint property that a layer can't set is skipped with a
/// warning; the layer keeps its other properties. That holds for a layer that
/// refers to another with `ref` too.
#[test]
fn invalid_properties_are_skipped() {
    let log = FixtureLog::new();
    let mut parser = Parser::new(&StyleRegistry::with_builtins());
    parser
        .parse(
            r#"{
        "version": 8,
        "sources": {"s": {"type": "geojson", "data": {"type": "FeatureCollection", "features": []}}},
        "layers": [
            {"id": "a", "type": "circle", "source": "s",
             "layout": {"visibility": "maybe", "circle-sort-key": 1},
             "paint": {"circle-color": "not a color", "circle-foo": 1, "circle-radius": 5}},
            {"id": "b", "ref": "a", "paint": {"circle-opacity": "opaque", "circle-radius": 7}}
        ]
    }"#,
        )
        .unwrap();

    let ids: Vec<_> = parser.layers.iter().map(super::super::layer::Layer::id).collect();
    assert_eq!(ids, ["a", "b"]);
    let property = |layer: usize, name: &str| {
        let property = parser.layers[layer].property(name);
        (property.kind(), property.value().clone())
    };
    assert_eq!(property(0, "circle-radius"), (Kind::Constant, Value::Double(5.0)));
    assert_eq!(property(0, "circle-sort-key"), (Kind::Constant, Value::Double(1.0)));
    assert_eq!(property(0, "circle-color").0, Kind::Undefined);
    assert_eq!(property(0, "visibility").0, Kind::Undefined);
    assert_eq!(property(1, "circle-radius"), (Kind::Constant, Value::Double(7.0)));
    assert_eq!(property(1, "circle-opacity").0, Kind::Undefined);

    let mut warnings: Vec<_> = log.messages().into_iter().map(|message| message.msg).collect();
    warnings.sort();
    assert_eq!(
        warnings,
        [
            "Layer property is invalid error=layer 'a' doesn't support property 'circle-foo'",
            "Layer property is invalid error=value must be a number",
            "Layer property is invalid error=value must be a valid color",
            "Layer property is invalid error=value must be a valid enumeration value",
        ],
    );
}