Skip to main content

mln_style/property/
expression.rs

1use std::sync::Arc;
2
3use mln_wire::shared;
4
5use crate::collections::VecSet;
6use crate::expression::value::from_expression_values;
7use crate::expression::{
8    Dependency, EvaluationContext, Expr, GlobalStateMap, Value, ValueConverter, ZoomCurve, collect_global_state_refs,
9    collect_host_function_refs, find_zoom_curve_checked,
10};
11use crate::range::Range;
12use crate::wire::SharedExpression;
13
14fn collect_global_state_refs_shared(expression: &Expr) -> Option<Arc<VecSet<String>>> {
15    if !expression.has(Dependency::GLOBAL_STATE) {
16        return None;
17    }
18    let mut refs = VecSet::new();
19    collect_global_state_refs(expression, &mut refs);
20    Some(Arc::new(refs))
21}
22
23fn collect_host_function_refs_shared(expression: &Expr) -> Option<Arc<VecSet<String>>> {
24    if !expression.has(Dependency::HOST) {
25        return None;
26    }
27    let mut refs = VecSet::new();
28    collect_host_function_refs(expression, &mut refs);
29    Some(Arc::new(refs))
30}
31
32/// A shared expression plus its precomputed constness flags. The zoom curve
33/// isn't cached, since it would borrow from the expression:
34/// `zoom_curve` finds it each time.
35#[derive(Clone, Debug)]
36pub struct PropertyExpressionBase {
37    expression: Arc<Expr>,
38    captured_global_state: Option<Arc<GlobalStateMap>>,
39    global_state_refs: Option<Arc<VecSet<String>>>,
40    host_function_refs: Option<Arc<VecSet<String>>>,
41    use_integer_zoom: bool,
42    global_state_pinned: bool,
43    is_zoom_constant: bool,
44    is_feature_constant: bool,
45    is_runtime_constant: bool,
46}
47
48impl PropertyExpressionBase {
49    pub(crate) fn new(expression: Arc<Expr>) -> Self {
50        let global_state_refs = collect_global_state_refs_shared(expression.as_ref());
51        let host_function_refs = collect_host_function_refs_shared(expression.as_ref());
52        let is_zoom_constant = !expression.has(Dependency::ZOOM);
53        let is_feature_constant = !expression.has(Dependency::FEATURE);
54        let is_runtime_constant = !expression.has(
55            Dependency::IMAGE | Dependency::GLOBAL_STATE | Dependency::CAMERA | Dependency::HOST | Dependency::TILE,
56        );
57        PropertyExpressionBase {
58            expression,
59            captured_global_state: None,
60            global_state_refs,
61            host_function_refs,
62            use_integer_zoom: false,
63            global_state_pinned: false,
64            is_zoom_constant,
65            is_feature_constant,
66            is_runtime_constant,
67        }
68    }
69
70    #[must_use]
71    pub fn is_zoom_constant(&self) -> bool {
72        self.is_zoom_constant
73    }
74
75    #[must_use]
76    pub fn is_feature_constant(&self) -> bool {
77        self.is_feature_constant
78    }
79
80    #[must_use]
81    pub(crate) fn is_runtime_constant(&self) -> bool {
82        self.is_runtime_constant
83    }
84
85    #[must_use]
86    pub fn interpolation_factor(&self, input_levels: Range<f64>, input_value: f64) -> f32 {
87        match self.zoom_curve() {
88            None => {
89                debug_assert!(false);
90                0.0
91            }
92            Some(ZoomCurve::Interpolate(z)) => z.interpolation_factor(input_levels, input_value) as f32,
93            Some(ZoomCurve::Step(_)) => 0.0,
94        }
95    }
96
97    #[must_use]
98    pub fn covering_stops(&self, lower: f64, upper: f64) -> Range<f64> {
99        match self.zoom_curve() {
100            None => {
101                debug_assert!(false);
102                Range::new(0.0, 0.0)
103            }
104            Some(ZoomCurve::Interpolate(z)) => z.covering_stops(lower, upper),
105            Some(ZoomCurve::Step(z)) => z.covering_stops(lower, upper),
106        }
107    }
108
109    /// The zooms of the stops of the expression's zoom curve, in order:
110    /// between them, it moves only one way from one stop's value to the
111    /// next's. Empty if it has no zoom curve.
112    #[must_use]
113    pub fn zoom_stops(&self) -> Vec<f64> {
114        match self.zoom_curve() {
115            None => Vec::new(),
116            Some(ZoomCurve::Interpolate(curve)) => curve.stop_inputs().collect(),
117            Some(ZoomCurve::Step(curve)) => curve.stop_inputs().collect(),
118        }
119    }
120
121    #[must_use]
122    pub fn expression(&self) -> &Expr {
123        self.expression.as_ref()
124    }
125
126    /// The expression, as the `Arc` that values of the property share.
127    #[must_use]
128    pub fn shared_expression(&self) -> &Arc<Expr> {
129        &self.expression
130    }
131
132    #[must_use]
133    pub fn use_integer_zoom(&self) -> bool {
134        self.use_integer_zoom
135    }
136
137    pub(crate) fn set_use_integer_zoom(&mut self, value: bool) {
138        self.use_integer_zoom = value;
139    }
140
141    /// Capture a snapshot of the style's global state so that later
142    /// evaluations (e.g. per-feature evaluation during tile layout or in
143    /// paint property binders) can resolve `global-state` expressions without
144    /// explicit plumbing. Only retained if the expression actually depends on
145    /// it.
146    pub fn capture_global_state(&mut self, global_state: Option<Arc<GlobalStateMap>>) {
147        if self.expression.has(Dependency::GLOBAL_STATE) && !self.global_state_pinned {
148            self.captured_global_state = global_state;
149        }
150    }
151
152    /// Evaluate `global-state` with this snapshot even when the evaluation
153    /// context carries a state of its own, so a value shown before a global
154    /// state change keeps its look while it transitions out. The first pin
155    /// wins: a value already showing an older state keeps showing it.
156    pub(crate) fn pin_global_state(&mut self, global_state: Arc<GlobalStateMap>) {
157        if self.global_state_pinned {
158            return;
159        }
160        self.captured_global_state = Some(global_state);
161        self.global_state_pinned = true;
162    }
163
164    #[must_use]
165    pub(crate) fn captured_global_state(&self) -> Option<&Arc<GlobalStateMap>> {
166        self.captured_global_state.as_ref()
167    }
168
169    /// None if the expression does not reference the global state.
170    #[must_use]
171    pub(crate) fn global_state_refs(&self) -> Option<&VecSet<String>> {
172        self.global_state_refs.as_deref()
173    }
174
175    /// None if the expression does not call any host-dependent function.
176    #[must_use]
177    pub(crate) fn host_function_refs(&self) -> Option<&VecSet<String>> {
178        self.host_function_refs.as_deref()
179    }
180
181    #[must_use]
182    pub(crate) fn dependencies(&self) -> Dependency {
183        self.expression.dependencies()
184    }
185
186    /// The expression's zoom curve (recomputed, see the struct comment).
187    #[must_use]
188    pub(crate) fn zoom_curve(&self) -> Option<ZoomCurve<'_>> {
189        find_zoom_curve_checked(self.expression.as_ref())
190    }
191}
192
193/// Crosses as the expression (shared, see wire.rs)
194/// and what was set on it; the flags are derived from the expression again.
195///
196/// Not inlined: every `PropertyExpression<T>`, `PropertyValue<T>` and
197/// `Evaluated<T>` reads and writes one, so inlined it would compile once per
198/// value type.
199impl mln_wire::Wire for PropertyExpressionBase {
200    #[inline(never)]
201    fn write(&self, w: &mut mln_wire::Writer<'_>) {
202        shared::write::<SharedExpression>(&self.expression, w);
203        self.captured_global_state.write(w);
204        self.use_integer_zoom.write(w);
205        self.global_state_pinned.write(w);
206    }
207
208    #[inline(never)]
209    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
210        let mut base = PropertyExpressionBase::new(shared::read::<SharedExpression>(r)?);
211        base.captured_global_state = mln_wire::Wire::read(r)?;
212        base.use_integer_zoom = mln_wire::Wire::read(r)?;
213        base.global_state_pinned = mln_wire::Wire::read(r)?;
214        Some(base)
215    }
216}
217
218#[derive(Clone, Debug, mln_wire::Wire)]
219pub struct PropertyExpression<T> {
220    base: PropertyExpressionBase,
221    /// A legacy function's `default`, for values its expression can't
222    /// convert to `T`, such as a string that names no enum value. Held as
223    /// a value rather than a `T`, so that only one copy of the code that
224    /// clones and sends it is compiled.
225    default_value: Option<Value>,
226    output: std::marker::PhantomData<fn() -> T>,
227}
228
229impl<T> std::ops::Deref for PropertyExpression<T> {
230    type Target = PropertyExpressionBase;
231    fn deref(&self) -> &PropertyExpressionBase {
232        &self.base
233    }
234}
235
236impl<T> std::ops::DerefMut for PropertyExpression<T> {
237    fn deref_mut(&mut self) -> &mut PropertyExpressionBase {
238        &mut self.base
239    }
240}
241
242impl<T> PropertyExpression<T> {
243    #[must_use]
244    pub fn new(expression: Arc<Expr>) -> Self {
245        PropertyExpression {
246            base: PropertyExpressionBase::new(expression),
247            default_value: None,
248            output: std::marker::PhantomData,
249        }
250    }
251
252    #[must_use]
253    pub fn from_expr(expression: Expr) -> Self {
254        PropertyExpression::new(Arc::new(expression))
255    }
256
257    /// `base` evaluated as a `T`, with a `default_value` as in
258    /// [`Self::with_default`].
259    pub(crate) fn from_parts(base: PropertyExpressionBase, default_value: Option<Value>) -> Self {
260        PropertyExpression { base, default_value, output: std::marker::PhantomData }
261    }
262
263    /// Evaluates to `default_value` where the expression fails or its value
264    /// doesn't convert to `T`, rather than to the property's default.
265    #[must_use]
266    pub fn with_default(self, default_value: Option<T>) -> Self
267    where
268        T: ValueConverter,
269    {
270        PropertyExpression { default_value: default_value.map(|d| d.to_expression_value()), ..self }
271    }
272}
273
274impl<T: Clone + ValueConverter> PropertyExpression<T> {
275    pub fn evaluate(&self, context: &EvaluationContext<'_>, final_default_value: T) -> T {
276        // A pinned snapshot wins, and the captured one fills in for a context
277        // that carries no state.
278        match &self.base.captured_global_state {
279            Some(captured) if self.base.global_state_pinned || context.global_state.is_none() => {
280                let context_with_state = context.with_global_state(Some(captured.as_ref()));
281                self.evaluate_context(&context_with_state, final_default_value)
282            }
283            _ => self.evaluate_context(context, final_default_value),
284        }
285    }
286
287    pub(crate) fn possible_outputs(&self) -> Vec<Option<T>> {
288        from_expression_values::<T>(&self.base.expression.possible_outputs())
289    }
290
291    fn evaluate_context(&self, context: &EvaluationContext<'_>, final_default_value: T) -> T {
292        T::evaluate(&self.base.expression, context)
293            .or_else(|| self.default_value.as_ref().and_then(T::from_expression_value))
294            .unwrap_or(final_default_value)
295    }
296}
297
298impl<T> PartialEq for PropertyExpression<T> {
299    fn eq(&self, other: &Self) -> bool {
300        self.base.expression == other.base.expression
301    }
302}
303
304#[cfg(test)]
305#[path = "expression_test.rs"]
306mod tests;