Skip to main content

mln_style/style/
parse.rs

1// The style's text is read into a `serde_json_borrow` tree, whose strings
2// borrow from the text and whose objects keep their members in document
3// order (conversion/borrowed.rs). The message of a JSON
4// syntax error is serde_json's.
5
6use std::sync::Arc;
7
8use crate::collections::VecSet;
9use crate::constants::DEFAULT_TRANSITION_DURATION;
10use crate::conversion::borrowed::{Json, JsonObject, borrowed_json_to_value, member, members};
11use crate::conversion::{Convertible, Error, convert};
12use crate::expression::GlobalStateMap;
13use crate::font_face::{FontFace, FontFaceRange, FontFaces};
14use crate::geo::LatLng;
15use crate::hash::{HashMap, HashSet};
16use crate::layer::{FontStack, InvalidProperty, Layer, convert_layer_with, set_paint_properties};
17use crate::light::{Light, convert_light};
18use crate::log_target;
19use crate::member::{Members, Place, is_extension_member};
20use crate::projection::{Projection, convert_projection};
21use crate::property::transition::TransitionOptions;
22use crate::registry::StyleRegistry;
23use crate::sky::{Sky, convert_sky};
24use crate::source::{Source, convert_source};
25use crate::sprite::Sprite;
26use crate::terrain::{Terrain, convert_terrain};
27
28/// What `Parser::parse` returns: a style that isn't one fails with
29/// [`ErrorKind::InvalidArgument`](crate::error::ErrorKind).
30pub(crate) type StyleParseResult = Result<(), crate::error::Error>;
31
32/// Reads a style's JSON, against the expression functions and layer types of
33/// a [`StyleRegistry`].
34pub struct Parser {
35    registry: Arc<StyleRegistry>,
36    pub sprites: Vec<Sprite>,
37    pub glyph_url: String,
38    pub font_faces: Option<Arc<FontFaces>>,
39    pub sources: Vec<Source>,
40    pub(crate) layers: Vec<Layer>,
41
42    pub(crate) transition: TransitionOptions,
43    pub(crate) light: Light,
44    pub(crate) sky: Option<Sky>,
45    pub(crate) terrain: Option<Terrain>,
46    pub(crate) projection: Projection,
47    /// The root's extension members.
48    pub(crate) members: Members,
49
50    /// Default values of the root "state" property, keyed by state property
51    /// name, used by the "global-state" expression.
52    pub(crate) global_state_defaults: GlobalStateMap,
53
54    pub(crate) name: String,
55    pub(crate) lat_lng: LatLng,
56    pub(crate) zoom: f64,
57    pub(crate) bearing: f64,
58    pub(crate) pitch: f64,
59    pub(crate) roll: f64,
60    pub(crate) center_altitude: f64,
61}
62
63impl Parser {
64    /// A parser of styles whose layers and expressions are `registry`'s.
65    #[must_use]
66    pub fn new(registry: &Arc<StyleRegistry>) -> Self {
67        Parser {
68            registry: Arc::clone(registry),
69            sprites: Vec::new(),
70            glyph_url: String::new(),
71            font_faces: None,
72            sources: Vec::new(),
73            layers: Vec::new(),
74            transition: TransitionOptions::with_duration(DEFAULT_TRANSITION_DURATION),
75            light: Light::new(),
76            sky: None,
77            terrain: None,
78            projection: Projection::new(),
79            members: Members::default(),
80            global_state_defaults: GlobalStateMap::new(),
81            name: String::new(),
82            lat_lng: LatLng::default(),
83            zoom: 0.0,
84            bearing: 0.0,
85            pitch: 0.0,
86            roll: 0.0,
87            center_altitude: 0.0,
88        }
89    }
90}
91
92impl Parser {
93    /// The style's projection.
94    #[must_use]
95    pub fn projection(&self) -> &Projection {
96        &self.projection
97    }
98}
99
100fn is_number(value: &Json<'_>) -> bool {
101    value.is_number()
102}
103
104fn number_or_zero(value: &Json<'_>) -> f64 {
105    value.as_f64().unwrap_or(0.0)
106}
107
108impl Parser {
109    pub fn parse(&mut self, json: &str) -> StyleParseResult {
110        let document: Json<'_> = match serde_json::from_str(json) {
111            Ok(document) => document,
112            Err(error) => return Err(crate::error::Error::invalid_argument(error.to_string())),
113        };
114
115        let Some(object) = document.as_object() else {
116            return Err(crate::error::Error::invalid_argument("style must be an object"));
117        };
118
119        if let Some(version_value) = member(object, "version") {
120            // A number's integer part; anything else is no version.
121            let version = if is_number(version_value) {
122                version_value.as_i64().unwrap_or_else(|| number_or_zero(version_value) as i64)
123            } else {
124                0
125            };
126            if version != 8 {
127                tracing::warn!(
128                    target: log_target::PARSE_STYLE,
129                    "current renderer implementation only supports style spec version 8; using an outdated style will cause rendering errors"
130                );
131            }
132        }
133
134        if let Some(value) = member(object, "name")
135            && let Some(name) = value.as_str()
136        {
137            self.name = name.to_owned();
138        }
139
140        if let Some(value) = member(object, "center") {
141            let mut error = Error::default();
142            match convert::<LatLng>(&Convertible::from(value), &mut error) {
143                Some(lat_lng) => self.lat_lng = lat_lng,
144                None => {
145                    tracing::warn!(target: log_target::PARSE_STYLE, "center coordinate must be a longitude, latitude pair");
146                }
147            }
148        }
149
150        if let Some(value) = member(object, "centerAltitude")
151            && is_number(value)
152        {
153            self.center_altitude = number_or_zero(value);
154        }
155
156        if let Some(value) = member(object, "zoom")
157            && is_number(value)
158        {
159            self.zoom = number_or_zero(value);
160        }
161
162        if let Some(value) = member(object, "bearing")
163            && is_number(value)
164        {
165            self.bearing = number_or_zero(value);
166        }
167
168        if let Some(value) = member(object, "pitch")
169            && is_number(value)
170        {
171            self.pitch = number_or_zero(value);
172        }
173
174        if let Some(value) = member(object, "roll")
175            && is_number(value)
176        {
177            self.roll = number_or_zero(value);
178        }
179
180        if let Some(value) = member(object, "transition") {
181            self.parse_transition(value);
182        }
183
184        if let Some(value) = member(object, "light") {
185            self.parse_light(value);
186        }
187
188        if let Some(value) = member(object, "terrain") {
189            self.parse_terrain(value);
190        }
191        if let Some(value) = member(object, "sky") {
192            self.parse_sky(value);
193        }
194
195        if let Some(value) = member(object, "projection") {
196            self.parse_projection(value);
197        }
198
199        if let Some(value) = member(object, "state") {
200            self.parse_state(value);
201        }
202
203        if let Some(value) = member(object, "sources") {
204            self.parse_sources(value);
205        }
206
207        if let Some(value) = member(object, "layers") {
208            self.parse_layers(value);
209        }
210
211        if let Some(value) = member(object, "sprite") {
212            self.parse_sprites(value);
213        }
214
215        if let Some(glyphs) = member(object, "glyphs")
216            && let Some(glyphs) = glyphs.as_str()
217        {
218            self.glyph_url = glyphs.to_owned();
219        }
220
221        if let Some(faces) = member(object, "font-faces")
222            && let Some(faces) = faces.as_object()
223        {
224            self.font_faces = Some(Arc::new(parse_font_faces(faces)));
225        }
226
227        for (name, value) in members(object) {
228            if is_extension_member(name) {
229                self.parse_member(name, value);
230            }
231        }
232
233        // Call for side effect of logging warnings for invalid values.
234        let _ = self.font_stacks();
235
236        Ok(())
237    }
238
239    fn parse_transition(&mut self, value: &Json<'_>) {
240        let mut error = Error::default();
241        let Some(converted) = convert::<TransitionOptions>(&Convertible::from(value), &mut error) else {
242            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style transition is invalid");
243            return;
244        };
245
246        self.transition = converted;
247    }
248
249    fn parse_light(&mut self, value: &Json<'_>) {
250        let mut error = Error::default();
251        let Some(converted) = convert_light(&Convertible::from(value), self.registry.functions(), &mut error) else {
252            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style light is invalid");
253            return;
254        };
255
256        self.light = converted;
257    }
258
259    fn parse_sky(&mut self, value: &Json<'_>) {
260        let mut error = Error::default();
261        let Some(converted) = convert_sky(&Convertible::from(value), self.registry.functions(), &mut error) else {
262            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style sky is invalid");
263            return;
264        };
265
266        self.sky = Some(converted);
267    }
268
269    fn parse_terrain(&mut self, value: &Json<'_>) {
270        let mut error = Error::default();
271        let Some(converted) = convert_terrain(&Convertible::from(value), &mut error) else {
272            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style terrain is invalid");
273            return;
274        };
275
276        self.terrain = Some(converted);
277    }
278
279    fn parse_projection(&mut self, value: &Json<'_>) {
280        let mut error = Error::default();
281        let Some(converted) = convert_projection(&Convertible::from(value), self.registry.functions(), &mut error)
282        else {
283            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style projection is invalid");
284            return;
285        };
286
287        self.projection = converted;
288    }
289
290    fn parse_member(&mut self, name: &str, value: &Json<'_>) {
291        match self.registry.member_value(Place::Root, name, &Convertible::from(value)) {
292            Ok(value) => self.members.set(name, value),
293            Err(error) => {
294                tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style member is invalid");
295            }
296        }
297    }
298
299    fn parse_state(&mut self, value: &Json<'_>) {
300        let Some(object) = value.as_object() else {
301            tracing::warn!(target: log_target::PARSE_STYLE, "state must be an object");
302            return;
303        };
304
305        for (property_name, definition) in members(object) {
306            let Some(member_object) = definition.as_object() else {
307                tracing::warn!(target: log_target::PARSE_STYLE, property = property_name, "state property must be an object");
308                continue;
309            };
310            let Some(default) = member(member_object, "default") else {
311                continue;
312            };
313            // emplace: the first definition wins.
314            self.global_state_defaults
315                .entry(property_name.to_owned())
316                .or_insert_with(|| borrowed_json_to_value(default));
317        }
318    }
319
320    fn parse_sources(&mut self, value: &Json<'_>) {
321        let Some(object) = value.as_object() else {
322            tracing::warn!(target: log_target::PARSE_STYLE, "sources must be an object");
323            return;
324        };
325
326        for (id, property) in members(object) {
327            let mut error = Error::default();
328            let Some(source) = convert_source(&Convertible::from(property), &mut error, id, &self.registry) else {
329                tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style source is invalid");
330                continue;
331            };
332
333            self.sources.push(source);
334        }
335    }
336
337    fn parse_sprites(&mut self, value: &Json<'_>) {
338        if let Some(url) = value.as_str() {
339            let sprite = Sprite::new("default", url);
340            self.sprites.push(sprite);
341        } else if let Some(array) = value.as_array() {
342            let mut sprite_ids = HashSet::default();
343            for sprite_value in array {
344                if !sprite_value.is_object() {
345                    tracing::warn!(target: log_target::PARSE_STYLE, "sprite child must be an object");
346                    continue;
347                }
348
349                let mut error = Error::default();
350                let Some(sprite) = convert::<Sprite>(&Convertible::from(sprite_value), &mut error) else {
351                    tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style sprite is invalid");
352                    continue;
353                };
354
355                if sprite_ids.contains(&sprite.id) {
356                    tracing::warn!(target: log_target::PARSE_STYLE, "sprite ids must be unique");
357                    continue;
358                }
359
360                sprite_ids.insert(sprite.id.clone());
361                self.sprites.push(sprite);
362            }
363        } else {
364            tracing::warn!(target: log_target::PARSE_STYLE, "sprite must be an object or string");
365        }
366    }
367
368    fn parse_layers(&mut self, value: &Json<'_>) {
369        let mut ids: Vec<String> = Vec::new();
370
371        let Some(array) = value.as_array() else {
372            tracing::warn!(target: log_target::PARSE_STYLE, "layers must be an array");
373            return;
374        };
375
376        let mut layers_map: HashMap<String, LayerEntry<'_>> = HashMap::default();
377
378        for layer_value in array {
379            let Some(layer_object) = layer_value.as_object() else {
380                tracing::warn!(target: log_target::PARSE_STYLE, "layer must be an object");
381                continue;
382            };
383
384            let Some(id) = member(layer_object, "id") else {
385                tracing::warn!(target: log_target::PARSE_STYLE, "layer must have an id");
386                continue;
387            };
388
389            let Some(id) = id.as_str() else {
390                tracing::warn!(target: log_target::PARSE_STYLE, "layer id must be a string");
391                continue;
392            };
393
394            let layer_id = id.to_owned();
395            if layers_map.contains_key(&layer_id) {
396                tracing::warn!(target: log_target::PARSE_STYLE, layer_id = %layer_id, "duplicate layer id");
397                continue;
398            }
399
400            layers_map.insert(layer_id.clone(), LayerEntry { value: layer_value, layer: None });
401            ids.push(layer_id);
402        }
403
404        // Store a stack of layer IDs we're parsing right now. This is to
405        // prevent reference cycles.
406        let mut stack: Vec<String> = Vec::new();
407
408        for id in &ids {
409            if layers_map.contains_key(id) {
410                parse_layer(&self.registry, id, &mut layers_map, &mut stack);
411            }
412        }
413
414        for id in &ids {
415            if let Some(entry) = layers_map.get_mut(id)
416                && let Some(layer) = entry.layer.take()
417            {
418                self.layers.push(layer);
419            }
420        }
421    }
422
423    /// Statically evaluate layer properties to determine what font stacks are used.
424    #[must_use]
425    pub fn font_stacks(&self) -> VecSet<FontStack> {
426        crate::layer::font_stacks(self.layers.iter().map(Layer::style))
427    }
428}
429
430struct LayerEntry<'a> {
431    value: &'a Json<'a>,
432    layer: Option<Layer>,
433}
434
435fn parse_layer(
436    registry: &StyleRegistry,
437    id: &str,
438    layers_map: &mut HashMap<String, LayerEntry<'_>>,
439    stack: &mut Vec<String>,
440) {
441    let Some(entry) = layers_map.get(id) else {
442        return;
443    };
444    if entry.layer.is_some() {
445        // Skip parsing this again. We already have a valid layer definition.
446        return;
447    }
448    let value = entry.value;
449
450    // Make sure we have not previously attempted to parse this layer.
451    if stack.iter().any(|s| s == id) {
452        tracing::warn!(target: log_target::PARSE_STYLE, layer_id = id, "layer reference is circular");
453        return;
454    }
455
456    if let Some(ref_val) = value.as_object().and_then(|object| member(object, "ref")) {
457        // This layer is referencing another layer. Recursively parse that layer.
458        let Some(ref_) = ref_val.as_str() else {
459            tracing::warn!(target: log_target::PARSE_STYLE, layer_id = id, "layer ref must be a string");
460            return;
461        };
462
463        if !layers_map.contains_key(ref_) {
464            tracing::warn!(target: log_target::PARSE_STYLE, layer_id = id, ref_layer_id = ref_, "layer references an unknown layer");
465            return;
466        }
467
468        // Recursively parse the referenced layer.
469        stack.insert(0, id.to_owned());
470        parse_layer(registry, ref_, layers_map, stack);
471        stack.remove(0);
472
473        let Some(reference) = layers_map.get(ref_).and_then(|e| e.layer.as_ref()) else {
474            return;
475        };
476
477        let mut layer = reference.clone_ref(id);
478        if let Some(error) = set_paint_properties(&mut layer, &Convertible::from(value), InvalidProperty::Skip) {
479            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Layer paint properties are invalid");
480        }
481        if let Some(entry) = layers_map.get_mut(id) {
482            entry.layer = Some(layer);
483        }
484    } else {
485        let mut error = Error::default();
486        let Some(converted) =
487            convert_layer_with(registry, &Convertible::from(value), &mut error, InvalidProperty::Skip)
488        else {
489            tracing::warn!(target: log_target::PARSE_STYLE, error = %error.message, "Style layer is invalid");
490            return;
491        };
492        if let Some(entry) = layers_map.get_mut(id) {
493            entry.layer = Some(converted);
494        }
495    }
496}
497
498/// Parses a font file of a font face: an object with a `url`, and with an
499/// optional `unicode-range` that limits the code points the font draws. Adds a
500/// warning for each range it can't read, and skips the range.
501fn parse_font_file(face_name: &str, font_file: &JsonObject<'_>, warnings: &mut Vec<String>) -> FontFace {
502    let mut font_face = FontFace { name: face_name.to_owned(), url: String::new(), ranges: vec![ALL_CODE_POINTS] };
503
504    if let Some(url) = member(font_file, "url").and_then(Json::as_str) {
505        font_face.url = url.to_owned();
506    }
507
508    if let Some(unicode_range) = member(font_file, "unicode-range") {
509        font_face.ranges.clear();
510        if let Some(ranges) = unicode_range.as_array() {
511            for range in ranges {
512                let Some(range_string) = range.as_str() else {
513                    continue;
514                };
515                if range_string.len() <= 2 {
516                    continue;
517                }
518                // Skips the `U+` prefix's bytes; the range is ASCII if it's
519                // valid.
520                let range_string = &range_string.as_bytes()[2..];
521                let Some(pos) = range_string.iter().position(|&b| b == b'-') else {
522                    continue;
523                };
524                let (start, end) = (&range_string[..pos], &range_string[pos + 1..]);
525                if start.is_empty() || end.is_empty() {
526                    continue;
527                }
528                // Each end is a whole hex number.
529                let parse = |s: &[u8]| {
530                    let s = std::str::from_utf8(s).ok()?;
531                    u32::from_str_radix(s, 16).ok()
532                };
533                match (parse(start), parse(end)) {
534                    (Some(start), Some(end)) => font_face.ranges.push((start, end)),
535                    _ => warnings
536                        .push(format!("Invalid unicode-range in font-face: {}", String::from_utf8_lossy(range_string))),
537                }
538            }
539        }
540    }
541
542    font_face
543}
544
545/// Parses fallback font faces from `json`, an array of font files in the format
546/// of a font face in a style's `font-faces`, without a font name. It fails with
547/// [`ErrorKind::InvalidArgument`](crate::error::ErrorKind) if `json` isn't such an
548/// array.
549pub fn parse_fallback_font_faces(json: &str) -> Result<FontFaces, crate::error::Error> {
550    let document: Json<'_> =
551        serde_json::from_str(json).map_err(|error| crate::error::Error::invalid_argument(error.to_string()))?;
552    let Some(files) = document.as_array() else {
553        return Err(crate::error::Error::invalid_argument("fallback font faces must be an array"));
554    };
555
556    let mut font_faces = FontFaces::new();
557    for font_file in files {
558        let Some(font_file) = font_file.as_object() else {
559            return Err(crate::error::Error::invalid_argument("each fallback font face must be an object"));
560        };
561        let mut warnings = Vec::new();
562        let font_face = parse_font_file("", font_file, &mut warnings);
563        if let Some(warning) = warnings.into_iter().next() {
564            return Err(crate::error::Error::invalid_argument(warning));
565        }
566        if font_face.url.is_empty() {
567            return Err(crate::error::Error::invalid_argument("each fallback font face must have a url"));
568        }
569        if font_face.ranges.is_empty() {
570            return Err(crate::error::Error::invalid_argument("each fallback font face must cover a unicode-range"));
571        }
572        font_faces.push(font_face);
573    }
574    Ok(font_faces)
575}
576
577/// The "font-faces" block of `Parser::parse` (`MLN_TEXT_SHAPING_HARFBUZZ`).
578fn parse_font_faces(faces: &JsonObject<'_>) -> FontFaces {
579    let mut font_faces = FontFaces::new();
580    for (face_name, face_value) in members(faces) {
581        if let Some(files) = face_value.as_array() {
582            // If the face is an array, we assume it is a list of font file
583            // objects.
584            for font_file in files {
585                let Some(font_file) = font_file.as_object() else {
586                    continue;
587                };
588                let mut warnings = Vec::new();
589                let font_face = parse_font_file(face_name, font_file, &mut warnings);
590                for warning in warnings {
591                    tracing::warn!(target: log_target::PARSE_STYLE, warning = %warning, "Font-face definition is invalid");
592                }
593
594                if !font_face.name.is_empty() && !font_face.url.is_empty() && !font_face.ranges.is_empty() {
595                    font_faces.push(font_face);
596                } else {
597                    tracing::warn!(target: log_target::PARSE_STYLE, font_face = face_name, "Invalid font-face definition");
598                }
599            }
600        } else if let Some(url) = face_value.as_str() {
601            font_faces.push(FontFace {
602                name: face_name.to_owned(),
603                url: url.to_owned(),
604                ranges: vec![ALL_CODE_POINTS],
605            });
606        } else {
607            tracing::warn!(target: log_target::PARSE_STYLE, "font-face must be an object or array");
608        }
609    }
610    font_faces
611}
612
613/// The range of a font face without a `unicode-range`: every code point.
614const ALL_CODE_POINTS: FontFaceRange = (0, 0x0010_FFFF);
615
616#[cfg(test)]
617#[path = "parse_test.rs"]
618mod tests;