Skip to main content

mln_plugin/
expression.rs

1//! Host-agnostic custom expression function plugin API (`ExpressionPlugin`).
2//!
3//! Implement [`ExpressionPlugin`] to define a custom MapLibre style expression
4//! function that can be registered either directly in-process via
5//! `mln_engine::RegistryBuilder::add_expression_plugin` (native and Wasm) or
6//! over the MapLibre Native C Plugin ABI via `mln_plugin_c::RegistryBuilder`.
7
8use core::ops::{BitAnd, BitOr, BitOrAssign};
9
10use crate::types::{CanonicalTileId, Color, LatLng};
11
12/// Capability flags declaring which runtime inputs an expression overload
13/// reads beyond its explicit arguments.
14///
15/// Pure functions (`ExprCapabilities::NONE`) may be constant-folded by the
16/// style parser when all of their arguments are constant.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
18pub struct ExprCapabilities(u32);
19
20impl ExprCapabilities {
21    /// Pure function: depends only on its arguments.
22    pub const NONE: Self = Self(0);
23    /// Reads the live camera context (`ExprEvalCx::camera`).
24    pub const CAMERA: Self = Self(1 << 0);
25    /// Reads mutable host or platform state invalidated via
26    /// `invalidate_expression_functions`.
27    pub const HOST: Self = Self(1 << 1);
28    /// Reads the canonical tile ID (`ExprEvalCx::tile`).
29    pub const TILE: Self = Self(1 << 2);
30    /// Depends on the evaluated feature (prevents constant folding and
31    /// feature-group sharing).
32    pub const FEATURE: Self = Self(1 << 3);
33
34    /// Mask of all capability bits defined by this SDK.
35    pub const ALL: Self = Self(Self::CAMERA.0 | Self::HOST.0 | Self::TILE.0 | Self::FEATURE.0);
36
37    /// Creates a capability set from raw bitflags.
38    #[must_use]
39    pub const fn from_bits(bits: u32) -> Self {
40        Self(bits)
41    }
42
43    /// Returns the raw bitmask value.
44    #[must_use]
45    pub const fn bits(self) -> u32 {
46        self.0
47    }
48
49    /// Returns `true` when no capabilities are set.
50    #[must_use]
51    pub const fn is_empty(self) -> bool {
52        self.0 == 0
53    }
54
55    /// Returns `true` when all bits in `other` are set in `self`.
56    #[must_use]
57    pub const fn contains(self, other: Self) -> bool {
58        (self.0 & other.0) == other.0
59    }
60
61    /// Combines two capability sets.
62    #[must_use]
63    pub const fn union(self, other: Self) -> Self {
64        Self(self.0 | other.0)
65    }
66}
67
68impl BitOr for ExprCapabilities {
69    type Output = Self;
70
71    fn bitor(self, rhs: Self) -> Self {
72        Self(self.0 | rhs.0)
73    }
74}
75
76impl BitOrAssign for ExprCapabilities {
77    fn bitor_assign(&mut self, rhs: Self) {
78        self.0 |= rhs.0;
79    }
80}
81
82impl BitAnd for ExprCapabilities {
83    type Output = Self;
84
85    fn bitand(self, rhs: Self) -> Self {
86        Self(self.0 & rhs.0)
87    }
88}
89
90/// Static expression type for an overload parameter or return value.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub enum ExprType {
93    Null,
94    Boolean,
95    Number,
96    String,
97    Color,
98    Object,
99    Value,
100    Array { item: Box<ExprType>, len: Option<usize> },
101}
102
103impl ExprType {
104    /// Variable-length array of `item`.
105    #[must_use]
106    pub fn array(item: Self) -> Self {
107        Self::Array { item: Box::new(item), len: None }
108    }
109
110    /// Fixed-length array of `len` elements of `item`.
111    #[must_use]
112    pub fn array_n(item: Self, len: usize) -> Self {
113        Self::Array { item: Box::new(item), len: Some(len) }
114    }
115}
116
117/// Parameter list signature for an expression overload.
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub enum ExprParams {
120    /// Fixed arity with explicit parameter types.
121    Fixed(Vec<ExprType>),
122    /// Zero or more arguments, each matching the given element type.
123    Varargs(ExprType),
124}
125
126/// Static signature and declared capabilities of one expression overload.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct ExprOverloadDesc {
129    pub params: ExprParams,
130    pub result: ExprType,
131    pub capabilities: ExprCapabilities,
132}
133
134impl ExprOverloadDesc {
135    /// Creates a pure overload descriptor (`ExprCapabilities::NONE`).
136    #[must_use]
137    pub const fn new(params: ExprParams, result: ExprType) -> Self {
138        Self { params, result, capabilities: ExprCapabilities::NONE }
139    }
140
141    /// Sets the capability flags for this overload.
142    #[must_use]
143    pub const fn with_capabilities(mut self, capabilities: ExprCapabilities) -> Self {
144        self.capabilities = capabilities;
145        self
146    }
147}
148
149/// Read-only camera state supplied to `ExprCapabilities::CAMERA` overloads.
150#[derive(Clone, Copy, Debug, Default, PartialEq)]
151pub struct ExprCamera {
152    pub zoom: f64,
153    /// Bearing in degrees clockwise from north.
154    pub bearing: f64,
155    /// Pitch in degrees from nadir.
156    pub pitch: f64,
157    /// Roll in degrees.
158    pub roll: f64,
159    /// Vertical field of view in degrees.
160    pub field_of_view: f64,
161    /// Camera center in WGS84 degrees.
162    pub center: LatLng,
163    /// Center altitude in meters above sea level.
164    pub center_altitude: f64,
165    /// Viewport width in logical pixels.
166    pub viewport_width: f64,
167    /// Viewport height in logical pixels.
168    pub viewport_height: f64,
169    /// Ground resolution at the camera center in meters per logical pixel.
170    pub meters_per_pixel: f64,
171    /// Whether the map is currently rendering in globe projection.
172    pub is_globe: bool,
173}
174
175/// Read-only context passed to [`ExpressionPlugin::evaluate`].
176#[derive(Clone, Copy, Debug, Default, PartialEq)]
177pub struct ExprEvalCx<'a> {
178    /// Live camera state when available.
179    pub camera: Option<&'a ExprCamera>,
180    /// Canonical tile ID when evaluating in a tiled context.
181    pub tile: Option<CanonicalTileId>,
182}
183
184/// Evaluated argument passed to [`ExpressionPlugin::evaluate`].
185#[derive(Clone, Copy, Debug, PartialEq)]
186pub enum ExprArg<'a> {
187    Null,
188    Bool(bool),
189    Number(f64),
190    String(&'a str),
191    Color(Color),
192    /// Compact UTF-8 JSON array.
193    ArrayJson(&'a str),
194    /// Compact UTF-8 JSON object.
195    ObjectJson(&'a str),
196}
197
198/// Value returned by [`ExpressionPlugin::evaluate`].
199#[derive(Clone, Debug, Default, PartialEq)]
200pub enum ExprValue {
201    #[default]
202    Null,
203    Bool(bool),
204    Number(f64),
205    String(String),
206    Color(Color),
207    /// Arbitrary JSON value (commonly an array or object).
208    Json(String),
209}
210
211impl From<bool> for ExprValue {
212    fn from(value: bool) -> Self {
213        Self::Bool(value)
214    }
215}
216
217impl From<f64> for ExprValue {
218    fn from(value: f64) -> Self {
219        Self::Number(value)
220    }
221}
222
223impl From<String> for ExprValue {
224    fn from(value: String) -> Self {
225        Self::String(value)
226    }
227}
228
229impl From<&str> for ExprValue {
230    fn from(value: &str) -> Self {
231        Self::String(value.to_owned())
232    }
233}
234
235impl From<Color> for ExprValue {
236    fn from(value: Color) -> Self {
237        Self::Color(value)
238    }
239}
240
241/// A custom MapLibre style expression function implemented in Rust.
242///
243/// Implementations must be thread-safe (`Send + Sync + 'static`) because
244/// evaluation may run on the render thread, tile layout worker threads, or
245/// standalone expression evaluation threads concurrently.
246pub trait ExpressionPlugin: Send + Sync + 'static {
247    /// Operator name as written in style JSON (for example `"acme:scale"`).
248    fn name(&self) -> &str;
249
250    /// One or more overload signatures accepted by this function.
251    fn overloads(&self) -> Vec<ExprOverloadDesc>;
252
253    /// Evaluates the overload at `overload_index` against already-evaluated
254    /// `args` and optional runtime context `cx`.
255    fn evaluate(&self, overload_index: usize, args: &[ExprArg<'_>], cx: &ExprEvalCx<'_>) -> Result<ExprValue, String>;
256}