oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
//! Runtime value representations. Evaluation lives in the evaluator.

use indexmap::IndexMap;
use std::{borrow::Cow, fmt::Debug, rc::Rc};

/// Insertion-ordered engine map with string keys.
pub type ValueMap<'a> = IndexMap<String, Value<'a>>;

/// A per-render engine object such as a slot, closure, date or attribute bag.
pub trait Object<'a>: Debug {
    /// Stable engine type name used in diagnostics and dispatch.
    fn type_name(&self) -> &'static str;

    /// Exposes a static object for native downcasting when supported.
    fn as_any(&self) -> Option<&dyn std::any::Any> {
        None
    }

    /// Borrows the value represented by a transparent display wrapper, if present.
    fn underlying(&self) -> Option<&Value<'a>> {
        None
    }

    /// Reads an exposed named field.
    fn field(&self, _name: &str) -> Option<Value<'a>> {
        None
    }

    /// Calls an exposed method.
    fn method(
        &self,
        _name: &str,
        _args: Vec<Arg<'a, '_>>,
    ) -> Option<crate::error::Result<Value<'a>>> {
        None
    }

    /// Calls a callable object, if applicable.
    fn call(&self, _args: &[Value<'a>]) -> Option<crate::error::Result<Value<'a>>> {
        None
    }

    /// Indicates whether this object can be passed as a closure.
    fn is_callable(&self) -> bool {
        false
    }

    /// Returns the printable representation, if supported.
    fn display(&self) -> crate::error::Result<String> {
        Err(crate::error::Error::new(
            crate::error::ErrorKind::Render,
            format!("{} cannot be printed", self.type_name()),
            None,
        ))
    }

    /// Borrows the printable representation when it is already stored as text.
    ///
    /// If supplied, this must match the text returned by `display`.
    fn display_text(&self) -> Option<&str> {
        None
    }

    /// Indicates that the object's printable representation is trusted HTML.
    fn is_trusted_html(&self) -> bool {
        false
    }

    /// Expands an iterable object up to the supplied element limit.
    fn entries(&self, _limit: usize) -> crate::error::Result<Vec<(Value<'a>, Value<'a>)>> {
        Err(crate::error::Error::new(
            crate::error::ErrorKind::Render,
            format!("cannot iterate {}", self.type_name()),
            None,
        ))
    }

    /// Borrows the object's JSON representation.
    fn json_kind(&self) -> crate::encode::JsonKind<'_> {
        crate::encode::JsonKind::Null
    }
}

/// A value in one render. JSON inputs and strings may borrow the caller's data.
#[derive(Clone, Debug)]
pub enum Value<'a> {
    /// Missing or null.
    Null,
    /// Boolean.
    Bool(bool),
    /// Signed 64-bit integer.
    Int(i64),
    /// 64-bit float.
    Float(f64),
    /// A plain string requiring escaping in an escaped echo.
    Str(Cow<'a, str>),
    /// Trusted HTML.
    Html(Cow<'a, str>),
    /// Borrowed view data.
    Json(&'a serde_json::Value),
    /// A sequence of values.
    List(Vec<Value<'a>>),
    /// An insertion-ordered map.
    Map(ValueMap<'a>),
    /// A render-local engine object.
    Object(Rc<dyn Object<'a> + 'a>),
}

impl<'a> Value<'a> {
    /// Constructs a plain string.
    pub fn string(text: impl Into<Cow<'a, str>>) -> Self {
        Self::Str(text.into())
    }

    /// Constructs explicitly trusted HTML.
    pub fn html(text: impl Into<Cow<'a, str>>) -> Self {
        Self::Html(text.into())
    }

    /// Wraps an engine object for shared ownership during the render.
    pub fn object(object: impl Object<'a> + 'a) -> Self {
        Self::Object(Rc::new(object))
    }
}

pub(crate) fn owned_data_depth_error() -> crate::error::Error {
    crate::error::Error::new(
        crate::error::ErrorKind::Limit,
        "owned render data depth limit exceeded",
        None,
    )
}

impl Value<'_> {
    pub(crate) fn owned_depth_within(&self, remaining: usize) -> bool {
        match self {
            Self::List(items) => {
                remaining > 0
                    && items
                        .iter()
                        .all(|value| value.owned_depth_within(remaining - 1))
            }
            Self::Map(fields) => {
                remaining > 0
                    && fields
                        .values()
                        .all(|value| value.owned_depth_within(remaining - 1))
            }
            _ => true,
        }
    }

    pub(crate) fn discard_deep_owned(self) {
        let mut pending = vec![self];
        while let Some(value) = pending.pop() {
            match value {
                Self::List(items) => pending.extend(items),
                Self::Map(fields) => pending.extend(fields.into_values()),
                _ => {}
            }
        }
    }
}

pub(crate) const MAX_OWNED_DATA_DEPTH: usize = 128;

#[derive(Debug)]
struct RejectedOwnedData;

impl Object<'_> for RejectedOwnedData {
    fn type_name(&self) -> &'static str {
        "rejected owned render data"
    }

    fn as_any(&self) -> Option<&dyn std::any::Any> {
        Some(self)
    }

    fn display(&self) -> crate::error::Result<String> {
        Err(owned_data_depth_error())
    }
}

impl<'a> Value<'a> {
    pub(crate) fn is_rejected_owned_data(&self) -> bool {
        matches!(self, Self::Object(object) if object.as_any().is_some_and(|object| object.is::<RejectedOwnedData>()))
    }

    pub(crate) fn reject_if_too_deep(&mut self) {
        if !self.owned_depth_within(MAX_OWNED_DATA_DEPTH) {
            std::mem::replace(self, Self::object(RejectedOwnedData)).discard_deep_owned();
        }
    }

    pub(crate) fn clone_with_depth_bound(&self) -> Self {
        if self.owned_depth_within(MAX_OWNED_DATA_DEPTH) {
            self.clone()
        } else {
            Self::object(RejectedOwnedData)
        }
    }
}

pub(crate) fn check_owned_layer(layer: ValueMap<'_>) -> crate::error::Result<ValueMap<'_>> {
    if layer
        .values()
        .all(|value| value.owned_depth_within(MAX_OWNED_DATA_DEPTH))
    {
        return Ok(layer);
    }
    Value::Map(layer).discard_deep_owned();
    Err(owned_data_depth_error())
}

pub(crate) fn bound_owned_layer(layer: &mut ValueMap<'_>) {
    layer.values_mut().for_each(Value::reject_if_too_deep);
}

pub(crate) fn bounded_owned_layers<'a>(
    layers: impl IntoIterator<Item = ValueMap<'a>>,
) -> impl Iterator<Item = ValueMap<'a>> {
    let mut layers = layers.into_iter();
    let mut first = layers.next();
    if let Some(first) = &mut first {
        bound_owned_layer(first);
    }
    let rest = layers
        .map(|mut layer| {
            bound_owned_layer(&mut layer);
            layer
        })
        .collect::<Vec<_>>();
    first.into_iter().chain(rest)
}

/// A render-local callable accepted by library functions and methods.
pub trait Callable<'a> {
    /// Invokes this callable with positional values.
    fn call(&mut self, args: &[Value<'a>]) -> crate::error::Result<Value<'a>>;
}

/// One operand supplied to library dispatch.
pub enum Arg<'a, 'c> {
    /// An ordinary runtime value.
    Value(Value<'a>),
    /// A callable borrowed for the duration of dispatch.
    Closure(&'c mut dyn Callable<'a>),
}

impl<'a> Value<'a> {
    /// Borrows JSON scalars in their native runtime representation.
    pub fn scalar(&self) -> Self {
        match self {
            Self::Json(serde_json::Value::Null) => Self::Null,
            Self::Json(serde_json::Value::Bool(value)) => Self::Bool(*value),
            Self::Json(serde_json::Value::Number(value)) => value.as_i64().map_or_else(
                || Self::Float(value.as_f64().unwrap_or(f64::INFINITY)),
                Self::Int,
            ),
            Self::Json(serde_json::Value::String(value)) => Self::string(value.as_str()),
            Self::Object(object) => object
                .underlying()
                .map_or_else(|| self.clone(), Self::scalar),
            value => value.clone(),
        }
    }

    /// Reports the runtime type used by diagnostics.
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Null | Self::Json(serde_json::Value::Null) => "None",
            Self::Bool(_) | Self::Json(serde_json::Value::Bool(_)) => "bool",
            Self::Int(_) => "i64",
            Self::Float(_) => "f64",
            Self::Str(_) | Self::Json(serde_json::Value::String(_)) => "string",
            Self::Html(_) => "HTML",
            Self::List(_) | Self::Json(serde_json::Value::Array(_)) => "list",
            Self::Map(_) | Self::Json(serde_json::Value::Object(_)) => "map",
            Self::Object(object) => object.type_name(),
            Self::Json(serde_json::Value::Number(number)) if number.is_i64() => "i64",
            Self::Json(serde_json::Value::Number(_)) => "f64",
        }
    }

    /// Returns whether this value represents an absent value.
    pub fn is_null(&self) -> bool {
        match self {
            Self::Object(object) => object.underlying().is_some_and(Self::is_null),
            value => matches!(value, Self::Null | Self::Json(serde_json::Value::Null)),
        }
    }

    /// Returns a string slice only for plain strings.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::Str(value) => Some(value),
            Self::Json(value) => value.as_str(),
            Self::Object(object) => object.underlying()?.as_str(),
            _ => None,
        }
    }

    /// Looks up a named field while preserving borrowed JSON.
    pub fn field(&self, name: &str) -> Option<Self> {
        match self {
            Self::Map(fields) => fields.get(name).cloned(),
            Self::Json(serde_json::Value::Object(fields)) => fields.get(name).map(Self::Json),
            Self::Object(object) => object.field(name),
            _ => None,
        }
    }

    /// Formats a scalar or printable object without escaping it.
    pub fn display(&self) -> crate::error::Result<String> {
        Ok(match self {
            Self::Str(value) | Self::Html(value) => value.to_string(),
            Self::Bool(value) => value.to_string(),
            Self::Int(value) => value.to_string(),
            Self::Float(value) => value.to_string(),
            Self::Null => String::new(),
            Self::Json(value) if !value.is_array() && !value.is_object() => {
                return self.scalar().display();
            }
            Self::Object(object) => return object.display(),
            _ => {
                return Err(crate::error::Error::new(
                    crate::error::ErrorKind::Render,
                    format!("{} cannot be printed", self.type_name()),
                    None,
                ));
            }
        })
    }

    /// Returns whether echoing the value bypasses escaping.
    pub fn is_trusted_html(&self) -> bool {
        match self {
            Self::Html(_) => true,
            Self::Object(object) => object.is_trusted_html(),
            _ => false,
        }
    }

    /// Iterates a list, map or iterable object as key-value pairs.
    pub fn entries(&self, limit: usize) -> crate::error::Result<Vec<(Self, Self)>> {
        let size = match self {
            Self::List(values) => values.len(),
            Self::Map(values) => values.len(),
            Self::Json(serde_json::Value::Array(values)) => values.len(),
            Self::Json(serde_json::Value::Object(values)) => values.len(),
            Self::Object(object) => return object.entries(limit),
            _ => {
                return Err(crate::error::Error::new(
                    crate::error::ErrorKind::Render,
                    format!("cannot iterate {}", self.type_name()),
                    None,
                ));
            }
        };
        if size > limit {
            return Err(expansion_error());
        }
        let indexed = |(index, value)| (Self::Int(index as i64), value);
        Ok(match self {
            Self::List(values) => values.iter().cloned().enumerate().map(indexed).collect(),
            Self::Map(values) => values
                .iter()
                .map(|(key, value)| (Self::string(key.clone()), value.clone()))
                .collect(),
            Self::Json(serde_json::Value::Array(values)) => values
                .iter()
                .map(Self::Json)
                .enumerate()
                .map(indexed)
                .collect(),
            Self::Json(serde_json::Value::Object(values)) => values
                .iter()
                .map(|(key, value)| (Self::string(key.as_str()), Self::Json(value)))
                .collect(),
            _ => Vec::new(),
        })
    }
}

pub(crate) fn expansion_error() -> crate::error::Error {
    crate::error::Error::new(
        crate::error::ErrorKind::Limit,
        "collection expansion limit exceeded",
        None,
    )
}

impl crate::encode::JsonValue for Value<'_> {
    fn json_kind(&self) -> crate::encode::JsonKind<'_> {
        use crate::encode::{ArrayKey, JsonKind, JsonValue};
        match self {
            Self::Null => JsonKind::Null,
            Self::Bool(value) => JsonKind::Bool(*value),
            Self::Int(value) => JsonKind::Integer(*value),
            Self::Float(value) => JsonKind::Float(*value),
            Self::Str(value) | Self::Html(value) => JsonKind::String(value.as_bytes()),
            Self::Json(value) => value.json_kind(),
            Self::List(values) => {
                JsonKind::Array(Box::new(values.iter().zip(0..).map(|(value, index)| {
                    (ArrayKey::Integer(index), value as &dyn JsonValue)
                })))
            }
            Self::Map(values) => {
                JsonKind::Array(Box::new(values.iter().map(|(key, value)| {
                    (ArrayKey::from(key.as_str()), value as &dyn JsonValue)
                })))
            }
            Self::Object(object) => object.json_kind(),
        }
    }
}