Skip to main content

mln_style/property/
table.rs

1//! The properties of a layer type, the light or the sky, as one table each,
2//! and the generic access by style-spec name that the style JSON, the runtime
3//! and the C API use.
4//!
5//! A table lists each property's name, whether it is paint or layout, and how
6//! its value converts. A property's slot is its index in the table. The type
7//! that holds the values implements `Properties`, which maps a slot to the
8//! field that holds it, typed, so that reading, converting and comparing a
9//! value needs no downcast.
10
11use std::cmp::Ordering;
12use std::sync::Arc;
13
14use crate::conversion::to_value::make_transition_style_property;
15use crate::conversion::{Converter, Convertible, Error};
16use crate::expression::Functions;
17use crate::feature::{Value, ValueObject};
18use crate::layer::PropertyScope;
19use crate::property::set::Transitionable;
20use crate::property::transition::PropertyTransition;
21use crate::property::value::StyleValue;
22
23/// One property in a [`PropertyTable`].
24#[derive(Debug)]
25pub struct PropertyInfo {
26    /// The style-spec name.
27    pub(crate) name: &'static str,
28    pub(crate) scope: PropertyScope,
29    /// Whether the value may be an expression that reads the feature.
30    pub(crate) data_driven: bool,
31    /// Whether a string constant's `{token}`s become an expression.
32    pub(crate) tokens: bool,
33    /// Whether a section of a formatted value can override the paint
34    /// property's value.
35    pub(crate) overridable: bool,
36    /// Whether the property is `cross-faded-data-driven` in the spec: its
37    /// values (patterns and dash arrays) are dependencies of the layout, so
38    /// any change to one lays the layer out again.
39    pub(crate) cross_faded: bool,
40    /// Whether a legacy function for this property may interpolate between
41    /// stops.
42    pub(crate) interpolated: bool,
43    /// Whether the value may be an expression that reads `["elevation"]`.
44    pub(crate) elevation: bool,
45}
46
47impl PropertyInfo {
48    #[must_use]
49    pub const fn paint(name: &'static str) -> Self {
50        PropertyInfo {
51            name,
52            scope: PropertyScope::Paint,
53            data_driven: false,
54            tokens: false,
55            overridable: false,
56            cross_faded: false,
57            interpolated: false,
58            elevation: false,
59        }
60    }
61
62    #[must_use]
63    pub const fn layout(name: &'static str) -> Self {
64        PropertyInfo {
65            name,
66            scope: PropertyScope::Layout,
67            data_driven: false,
68            tokens: false,
69            overridable: false,
70            cross_faded: false,
71            interpolated: false,
72            elevation: false,
73        }
74    }
75
76    #[must_use]
77    pub const fn data_driven(self) -> Self {
78        PropertyInfo { data_driven: true, ..self }
79    }
80
81    #[must_use]
82    pub const fn tokens(self) -> Self {
83        PropertyInfo { tokens: true, ..self }
84    }
85
86    #[must_use]
87    pub const fn overridable(self) -> Self {
88        PropertyInfo { overridable: true, ..self }
89    }
90
91    #[must_use]
92    pub const fn cross_faded(self) -> Self {
93        PropertyInfo { cross_faded: true, ..self }
94    }
95
96    #[must_use]
97    pub const fn interpolated(self) -> Self {
98        PropertyInfo { interpolated: true, ..self }
99    }
100
101    #[must_use]
102    pub const fn elevation(self) -> Self {
103        PropertyInfo { elevation: true, ..self }
104    }
105}
106
107/// The style-spec name of the property in the field `field`: the field's
108/// name with each `_` a `-`, as `N` bytes, `field`'s length.
109#[doc(hidden)]
110#[must_use]
111pub const fn property_name<const N: usize>(field: &str) -> [u8; N] {
112    let field = field.as_bytes();
113    assert!(field.len() == N, "the length is the field's");
114    let mut name = [0; N];
115    let mut i = 0;
116    while i < N {
117        name[i] = if field[i] == b'_' { b'-' } else { field[i] };
118        i += 1;
119    }
120    name
121}
122
123/// The slots of `properties`, sorted by name, as [`PropertyTable::new`]
124/// takes them. Fails the build for more than 256 properties or two of the
125/// same name.
126#[doc(hidden)]
127#[must_use]
128pub const fn slots_by_name<const N: usize>(properties: &[PropertyInfo; N]) -> [u8; N] {
129    assert!(N <= 256, "a table has at most 256 properties");
130    let mut slots = [0; N];
131    let mut i = 0;
132    while i < N {
133        slots[i] = i as u8;
134        // Insertion: move the new slot down past the names after its own.
135        let mut j = i;
136        while j > 0 {
137            let order = compare(properties[slots[j - 1] as usize].name, properties[slots[j] as usize].name);
138            assert!(!matches!(order, Ordering::Equal), "two properties have the same name");
139            if matches!(order, Ordering::Less) {
140                break;
141            }
142            let previous = slots[j - 1];
143            slots[j - 1] = slots[j];
144            slots[j] = previous;
145            j -= 1;
146        }
147        i += 1;
148    }
149    slots
150}
151
152/// `a.cmp(b)`, in a constant.
153const fn compare(a: &str, b: &str) -> Ordering {
154    let (a, b) = (a.as_bytes(), b.as_bytes());
155    let mut i = 0;
156    while i < a.len() && i < b.len() {
157        if a[i] != b[i] {
158            return if a[i] < b[i] { Ordering::Less } else { Ordering::Greater };
159        }
160        i += 1;
161    }
162    if a.len() < b.len() {
163        Ordering::Less
164    } else if a.len() > b.len() {
165        Ordering::Greater
166    } else {
167        Ordering::Equal
168    }
169}
170
171/// The properties of one layer type, the light or the sky, in the style
172/// spec's order: paint properties, then layout properties.
173#[derive(Debug)]
174pub struct PropertyTable {
175    properties: &'static [PropertyInfo],
176    /// The slots, sorted by property name.
177    by_name: &'static [u8],
178}
179
180impl PropertyTable {
181    /// `by_name` lists the slots of `properties` sorted by name.
182    #[must_use]
183    pub const fn new(properties: &'static [PropertyInfo], by_name: &'static [u8]) -> Self {
184        PropertyTable { properties, by_name }
185    }
186
187    /// The slot of the property named `name`.
188    #[must_use]
189    pub(crate) fn find(&self, name: &str) -> Option<usize> {
190        let index = self.by_name.binary_search_by(|&slot| self.properties[usize::from(slot)].name.cmp(name)).ok()?;
191        Some(usize::from(self.by_name[index]))
192    }
193
194    /// The property that `name` sets: a property, or with `transition` true a
195    /// paint property's `<name>-transition`.
196    fn resolve(&self, name: &str) -> Option<(usize, bool)> {
197        if let Some(slot) = self.find(name) {
198            return Some((slot, false));
199        }
200        let slot = self.find(name.strip_suffix("-transition")?)?;
201        (self.properties[slot].scope == PropertyScope::Paint).then_some((slot, true))
202    }
203}
204
205/// What to do with the field that holds a property, given functions that
206/// borrow it from the properties' owner `S`.
207pub trait PropertyVisitor<S> {
208    type Output;
209
210    fn paint<V: StyleValue>(
211        self,
212        get: fn(&S) -> &Transitionable<V>,
213        get_mut: fn(&mut S) -> &mut Transitionable<V>,
214    ) -> Self::Output;
215
216    fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) -> Self::Output;
217}
218
219/// A type that holds the values of the properties in a table.
220pub(crate) trait Properties: Clone + 'static {
221    const TABLE: &'static PropertyTable;
222
223    /// Calls `visitor` with the field of the property in `slot`, or returns
224    /// `None` for a slot past the table's end.
225    fn visit<V: PropertyVisitor<Self>>(slot: usize, visitor: V) -> Option<V::Output>;
226}
227
228/// Why setting a property failed.
229#[derive(Debug)]
230pub enum SetPropertyError {
231    /// The table has no property of that name.
232    Unknown,
233    /// The value doesn't convert.
234    Invalid(Error),
235}
236
237/// The property `name` (or a paint property's `<name>-transition`) of `owner`,
238/// undefined for a name the table lacks.
239pub(crate) fn property<S: Properties>(owner: &S, name: &str) -> StyleProperty {
240    match S::TABLE.resolve(name) {
241        Some((slot, transition)) => style_property(owner, slot, transition),
242        None => StyleProperty::default(),
243    }
244}
245
246fn style_property<S: Properties>(owner: &S, slot: usize, transition: bool) -> StyleProperty {
247    struct Get<'a, S> {
248        owner: &'a S,
249        transition: bool,
250    }
251
252    impl<S> PropertyVisitor<S> for Get<'_, S> {
253        type Output = StyleProperty;
254
255        fn paint<V: StyleValue>(
256            self,
257            get: fn(&S) -> &Transitionable<V>,
258            _: fn(&mut S) -> &mut Transitionable<V>,
259        ) -> StyleProperty {
260            paint_style_property(get(self.owner), self.transition)
261        }
262
263        fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> StyleProperty {
264            get(self.owner).style_property()
265        }
266    }
267
268    S::visit(slot, Get { owner, transition }).unwrap_or_default()
269}
270
271// The visitors' work is split by the type it depends on: what depends only on
272// the value type is in a function of its own, so that it compiles once per
273// value type rather than once per value type and owner. And what depends on
274// both is not inlined into `Properties::visit`, so that it compiles once per
275// pair rather than once per property.
276
277#[inline(never)]
278fn paint_style_property<V: StyleValue>(property: &Transitionable<V>, transition: bool) -> StyleProperty {
279    if transition { make_transition_style_property(&property.options) } else { property.value.style_property() }
280}
281
282/// Where the owner of properties is kept, for [`set_property`] to read it
283/// and to change it in place.
284pub(crate) trait OwnerSlot<S> {
285    /// The owner; `None` when the slot holds something else.
286    fn get(&self) -> Option<&S>;
287
288    /// The owner, to change: copied first if it is shared.
289    fn make_mut(&mut self) -> Option<&mut S>;
290}
291
292impl<S: Clone> OwnerSlot<S> for Arc<S> {
293    fn get(&self) -> Option<&S> {
294        Some(self)
295    }
296
297    #[inline(never)]
298    fn make_mut(&mut self) -> Option<&mut S> {
299        Some(Arc::make_mut(self))
300    }
301}
302
303/// An owner that isn't shared, changed in place.
304pub(crate) struct InPlace<'a, S>(pub(crate) &'a mut S);
305
306impl<S> OwnerSlot<S> for InPlace<'_, S> {
307    fn get(&self) -> Option<&S> {
308        Some(self.0)
309    }
310
311    fn make_mut(&mut self) -> Option<&mut S> {
312        Some(self.0)
313    }
314}
315
316/// Sets the property `name` (or a paint property's `<name>-transition`) of
317/// the owner in `owner` from a style JSON value, whose expressions parse
318/// against `functions`. The owner is copied only if the value changes it and
319/// it is shared.
320pub(crate) fn set_property<S: Properties, O: OwnerSlot<S>>(
321    owner: &mut O,
322    name: &str,
323    value: &Convertible<'_>,
324    functions: &Arc<Functions>,
325) -> Result<(), SetPropertyError> {
326    struct Set<'a, 'v, O> {
327        owner: &'a mut O,
328        value: &'a Convertible<'v>,
329        functions: &'a Arc<Functions>,
330        info: &'static PropertyInfo,
331        transition: bool,
332        error: &'a mut Option<Error>,
333    }
334
335    // The change passes through a slot of the caller's, rather than by value,
336    // so that this code, compiled for each pair of owner and value type, is
337    // only calls.
338    impl<S, O: OwnerSlot<S>> PropertyVisitor<S> for Set<'_, '_, O> {
339        type Output = ();
340
341        #[inline(never)]
342        fn paint<V: StyleValue>(
343            self,
344            get: fn(&S) -> &Transitionable<V>,
345            get_mut: fn(&mut S) -> &mut Transitionable<V>,
346        ) {
347            let mut change = PaintChange::None;
348            let Some(current) = self.owner.get() else { return };
349            if paint_change(
350                get(current),
351                self.value,
352                self.functions,
353                self.info,
354                self.transition,
355                &mut change,
356                self.error,
357            ) && let Some(owner) = self.owner.make_mut()
358            {
359                apply_paint_change(get_mut(owner), &mut change);
360            }
361        }
362
363        #[inline(never)]
364        fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) {
365            let mut change = None;
366            let Some(current) = self.owner.get() else { return };
367            if changed_value(get(current), self.value, self.functions, self.info, &mut change, self.error)
368                && let Some(owner) = self.owner.make_mut()
369            {
370                store(get_mut(owner), &mut change);
371            }
372        }
373    }
374
375    let (slot, transition) = S::TABLE.resolve(name).ok_or(SetPropertyError::Unknown)?;
376    let info = &S::TABLE.properties[slot];
377    let mut error = None;
378    S::visit(slot, Set { owner, value, functions, info, transition, error: &mut error })
379        .ok_or(SetPropertyError::Unknown)?;
380    error.map_or(Ok(()), |error| Err(SetPropertyError::Invalid(error)))
381}
382
383/// Sets `change` to `value` converted for the property `info` if it differs
384/// from `current`, and returns whether it does. Sets `error` if it doesn't
385/// convert.
386#[inline(never)]
387fn changed_value<V: StyleValue>(
388    current: &V,
389    value: &Convertible<'_>,
390    functions: &Arc<Functions>,
391    info: &PropertyInfo,
392    change: &mut Option<V>,
393    error: &mut Option<Error>,
394) -> bool {
395    match V::convert(value, info, functions) {
396        Ok(value) if *current != value => {
397            *change = Some(value);
398            true
399        }
400        Ok(_) => false,
401        Err(e) => {
402            *error = Some(e);
403            false
404        }
405    }
406}
407
408/// What setting a paint property changes.
409enum PaintChange<V> {
410    None,
411    Value(V),
412    Options(PropertyTransition),
413}
414
415/// Sets `change` to what setting a paint property's value, or with
416/// `transition` true its transition, to `value` changes, and returns whether
417/// it changes anything. Sets `error` if `value` doesn't convert.
418#[inline(never)]
419fn paint_change<V: StyleValue>(
420    current: &Transitionable<V>,
421    value: &Convertible<'_>,
422    functions: &Arc<Functions>,
423    info: &PropertyInfo,
424    transition: bool,
425    change: &mut PaintChange<V>,
426    error: &mut Option<Error>,
427) -> bool {
428    if transition {
429        let mut conversion_error = Error::default();
430        match <PropertyTransition as Converter>::convert(value, &mut conversion_error) {
431            Some(options) if current.options != options => *change = PaintChange::Options(options),
432            Some(_) => {}
433            None => *error = Some(conversion_error),
434        }
435    } else {
436        let mut new_value = None;
437        changed_value(&current.value, value, functions, info, &mut new_value, error);
438        if let Some(value) = new_value {
439            *change = PaintChange::Value(value);
440        }
441    }
442    !matches!(change, PaintChange::None)
443}
444
445#[inline(never)]
446fn apply_paint_change<V>(property: &mut Transitionable<V>, change: &mut PaintChange<V>) {
447    match std::mem::replace(change, PaintChange::None) {
448        PaintChange::None => {}
449        PaintChange::Value(value) => property.value = value,
450        PaintChange::Options(options) => property.options = options,
451    }
452}
453
454#[inline(never)]
455fn store<V>(slot: &mut V, change: &mut Option<V>) {
456    if let Some(value) = change.take() {
457        *slot = value;
458    }
459}
460
461/// Whether going from `a` to `b` changes a property that tiles are laid out
462/// with: a layout property, a cross-faded paint property, a data-driven
463/// paint property while either value differs by feature, or, with
464/// `section_overrides`, an overridable paint property's constant.
465pub(crate) fn layout_properties_differ<S: Properties>(a: &S, b: &S, section_overrides: bool) -> bool {
466    /// Which differences of a property's values count.
467    #[derive(Clone, Copy)]
468    struct Checks {
469        any: bool,
470        data_driven: bool,
471        constant: bool,
472    }
473
474    struct Differs<'a, S> {
475        a: &'a S,
476        b: &'a S,
477        checks: Checks,
478    }
479
480    impl<S> PropertyVisitor<S> for Differs<'_, S> {
481        type Output = bool;
482
483        fn paint<V: StyleValue>(
484            self,
485            get: fn(&S) -> &Transitionable<V>,
486            _: fn(&mut S) -> &mut Transitionable<V>,
487        ) -> bool {
488            values_differ(&get(self.a).value, &get(self.b).value, self.checks)
489        }
490
491        fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> bool {
492            values_differ(get(self.a), get(self.b), self.checks)
493        }
494    }
495
496    #[inline(never)]
497    fn values_differ<V: StyleValue>(a: &V, b: &V, checks: Checks) -> bool {
498        (checks.any && a != b)
499            || (checks.data_driven && a.has_data_driven_property_difference(b))
500            || (checks.constant && a.constant_differs(b))
501    }
502
503    S::TABLE.properties.iter().enumerate().any(|(slot, info)| {
504        let checks = Checks {
505            any: info.scope == PropertyScope::Layout || info.cross_faded,
506            data_driven: info.data_driven,
507            constant: section_overrides && info.overridable,
508        };
509        (checks.any || checks.data_driven || checks.constant)
510            && S::visit(slot, Differs { a, b, checks }).unwrap_or_default()
511    })
512}
513
514/// Each defined property of `owner` and paint property transition, in table
515/// order, with its name and scope.
516pub(crate) fn defined_properties<S: Properties>(owner: &S) -> Vec<(String, PropertyScope, StyleProperty)> {
517    defined_properties_in(S::TABLE, &|slot, transition| style_property(owner, slot, transition))
518}
519
520/// `defined_properties` over the `table` of an owner whose property in a slot
521/// `get` returns, compiled once rather than for each owner.
522fn defined_properties_in(
523    table: &PropertyTable,
524    get: &dyn Fn(usize, bool) -> StyleProperty,
525) -> Vec<(String, PropertyScope, StyleProperty)> {
526    let table = table.properties;
527    let mut defined = Vec::new();
528    let paint = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Paint);
529    let layout = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Layout);
530    let values = paint.clone().map(|(slot, info)| (slot, info, false));
531    let transitions = paint.map(|(slot, info)| (slot, info, true));
532    let layout = layout.map(|(slot, info)| (slot, info, false));
533    for (slot, info, transition) in values.chain(transitions).chain(layout) {
534        let property = get(slot, transition);
535        if property.kind() == Kind::Undefined {
536            continue;
537        }
538        let name = if transition { format!("{}-transition", info.name) } else { info.name.to_owned() };
539        defined.push((name, info.scope, property));
540    }
541    defined
542}
543
544/// Writes the defined properties of `owner` into a layer's style JSON `out`,
545/// under "paint" and "layout". A key already there stays.
546pub(crate) fn serialize_properties<S: Properties>(owner: &S, out: &mut ValueObject) {
547    insert_properties(defined_properties(owner), out);
548}
549
550fn insert_properties(defined: Vec<(String, PropertyScope, StyleProperty)>, out: &mut ValueObject) {
551    for (name, scope, property) in defined {
552        let key = match scope {
553            PropertyScope::Paint => "paint",
554            PropertyScope::Layout => "layout",
555        };
556        if let Some(Value::Object(existing)) = out.get_mut(key) {
557            existing.entry(name).or_insert_with(|| property.value().clone());
558        } else {
559            let mut inner = ValueObject::new();
560            inner.insert(name, property.value().clone());
561            out.insert(key.to_owned(), Value::Object(inner));
562        }
563    }
564}
565
566/// The names `S` accepts: each property, followed by its `-transition` for a
567/// paint property.
568pub(crate) fn names<S: Properties>() -> impl Iterator<Item = String> {
569    S::TABLE.properties.iter().flat_map(|info| {
570        let transition = (info.scope == PropertyScope::Paint).then(|| format!("{}-transition", info.name));
571        std::iter::once(info.name.to_owned()).chain(transition)
572    })
573}
574
575#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
576#[repr(u8)]
577pub enum Kind {
578    #[default]
579    Undefined,
580    Constant,
581    Expression,
582    Transition,
583}
584
585/// Generic representation of a style property.
586#[derive(Clone, Debug, Default, PartialEq)]
587pub struct StyleProperty {
588    value: Value,
589    kind: Kind,
590}
591
592impl StyleProperty {
593    #[must_use]
594    pub(crate) fn new(value: Value, kind: Kind) -> Self {
595        StyleProperty { value, kind }
596    }
597
598    #[must_use]
599    pub fn value(&self) -> &Value {
600        &self.value
601    }
602
603    #[must_use]
604    pub fn kind(&self) -> Kind {
605        self.kind
606    }
607}