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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::{
    error::{Error, ErrorKind, Result},
    library::{CallLimits, data_depth_error},
    value::{Arg, Callable, Value, ValueMap},
};
use serde_json::Value as Json;
use std::{cmp::Ordering, rc::Rc};

pub(super) type Row<'a> = (Value<'a>, Value<'a>);

pub(super) fn error(message: impl Into<String>) -> Error {
    Error::new(ErrorKind::Render, message, None)
}

pub(super) fn normalized<'a>(value: &Value<'a>) -> Value<'a> {
    value.scalar()
}

pub(super) fn is_null(value: &Value<'_>) -> bool {
    value.is_null()
}

pub(super) fn is_map(value: &Value<'_>) -> bool {
    matches!(value, Value::Map(_) | Value::Json(Json::Object(_)))
}

pub(super) fn is_list(value: &Value<'_>) -> bool {
    matches!(value, Value::List(_) | Value::Json(Json::Array(_)))
}

pub(super) fn is_collection(value: &Value<'_>) -> bool {
    is_list(value) || is_map(value)
}

pub(super) fn size(value: &Value<'_>) -> usize {
    match value {
        Value::List(items) => items.len(),
        Value::Map(items) => items.len(),
        Value::Json(Json::Array(items)) => items.len(),
        Value::Json(Json::Object(items)) => items.len(),
        _ => 0,
    }
}

pub(super) fn index<'a>(n: usize) -> Value<'a> {
    Value::Int(n as i64)
}

pub(super) fn rows<'a>(value: &Value<'a>) -> Result<Vec<Row<'a>>> {
    if !is_collection(value) {
        return Err(error("expected a list or map"));
    }
    let mut entries = value.entries(usize::MAX)?;
    for (_, value) in &mut entries {
        if matches!(value, Value::Json(_)) {
            *value = value.scalar();
        }
    }
    Ok(entries)
}

pub(super) fn values<'a>(value: &Value<'a>) -> Result<Vec<Value<'a>>> {
    Ok(rows(value)?.into_iter().map(|(_, v)| v).collect())
}

pub(super) fn collection<'a>(keyed: bool, rows: impl IntoIterator<Item = Row<'a>>) -> Value<'a> {
    if keyed {
        Value::Map(
            rows.into_iter()
                .map(|(k, v)| {
                    // Row keys originate from a collection or were validated before insertion.
                    let k = match k {
                        Value::Str(k) => k.into_owned(),
                        Value::Int(k) => k.to_string(),
                        _ => unreachable!("collection row keys are strings or integers"),
                    };
                    (k, v)
                })
                .collect(),
        )
    } else {
        Value::List(rows.into_iter().map(|(_, value)| value).collect())
    }
}

pub(super) fn key(value: &Value<'_>) -> Result<String> {
    match normalized(value) {
        Value::Str(s) => Ok(s.into_owned()),
        Value::Int(n) => Ok(n.to_string()),
        _ => Err(error("collection keys must be strings or integers")),
    }
}

pub(super) fn keys(value: &Value<'_>) -> Result<Vec<String>> {
    if is_collection(value) {
        values(value)?.iter().map(key).collect()
    } else {
        Ok(vec![key(value)?])
    }
}

pub(super) fn integer(value: &Value<'_>) -> Result<i64> {
    match normalized(value) {
        Value::Int(n) => Ok(n),
        _ => Err(error("expected an integer")),
    }
}

pub(super) fn string<'a>(value: &Value<'a>) -> Result<std::borrow::Cow<'a, str>> {
    match normalized(value) {
        Value::Str(s) => Ok(s),
        _ => Err(error("expected a string")),
    }
}

pub(super) fn boolean(value: &Value<'_>) -> Result<bool> {
    match normalized(value) {
        Value::Bool(b) => Ok(b),
        _ => Err(error("collection predicates must return a bool")),
    }
}

pub(super) fn signed_offset(len: usize, offset: i64) -> usize {
    if offset < 0 {
        len.saturating_sub(magnitude(offset))
    } else {
        len.min(magnitude(offset))
    }
}

pub(super) fn magnitude(n: i64) -> usize {
    usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX)
}

pub(super) fn get_key<'a>(value: &Value<'a>, key: &str) -> Option<Value<'a>> {
    let list_index = || key.parse::<usize>().ok().filter(|n| n.to_string() == key);
    match value {
        Value::List(items) => items.get(list_index()?).cloned(),
        Value::Json(Json::Array(items)) => items
            .get(list_index()?)
            .map(|v| normalized(&Value::Json(v))),
        _ => value.field(key).map(|v| normalized(&v)),
    }
}

/// Laravel's data_get descends each path segment and does not prefer a literal dotted key.
pub(super) fn data_get<'a>(
    value: &Value<'a>,
    path: &str,
    depth: usize,
) -> Result<Option<Value<'a>>> {
    fn descend<'a>(value: &Value<'a>, path: &[&str], depth: usize) -> Result<Option<Value<'a>>> {
        let mut current = value.clone();
        for (i, segment) in path.iter().enumerate() {
            let next = match *segment {
                "*" => {
                    let Ok(children) = values(&current) else {
                        return Ok(None);
                    };
                    let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
                    let rest = &path[i + 1..];
                    let flatten = rest.contains(&"*");
                    let mut found = Vec::new();
                    for child in children {
                        let hit = descend(&child, rest, depth)?.unwrap_or(Value::Null);
                        if flatten {
                            found.extend(values(&hit).unwrap_or_default());
                        } else {
                            found.push(hit);
                        }
                    }
                    return Ok(Some(Value::List(found)));
                }
                "{first}" => rows(&current)
                    .ok()
                    .and_then(|rows| rows.into_iter().next())
                    .map(|(_, item)| item),
                "{last}" => rows(&current)
                    .ok()
                    .and_then(|rows| rows.into_iter().next_back())
                    .map(|(_, item)| item),
                "\\*" | "\\{first}" | "\\{last}" => get_key(&current, &segment[1..]),
                segment => get_key(&current, segment),
            };
            let Some(next) = next else {
                return Ok(None);
            };
            current = next;
        }
        Ok(Some(current.scalar()))
    }
    descend(value, &path.split('.').collect::<Vec<_>>(), depth)
}

pub(super) fn get_path<'a>(value: &Value<'a>, path: &str) -> Option<Value<'a>> {
    get_key(value, path).or_else(|| {
        let (first, rest) = path.split_once('.')?;
        let mut current = get_key(value, first)?;
        for segment in rest.split('.') {
            current = get_key(&current, segment)?;
        }
        Some(current)
    })
}

pub(super) fn equal<'a>(a: &Value<'a>, b: &Value<'a>, depth: usize) -> Result<bool> {
    if is_map(a) && is_map(b) {
        if size(a) != size(b) {
            return Ok(false);
        }
        let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
        for (k, v) in rows(a)? {
            let Some(other) = get_key(b, &key(&k)?) else {
                return Ok(false);
            };
            if !equal(&v, &other, depth)? {
                return Ok(false);
            }
        }
        return Ok(true);
    }
    if is_list(a) && is_list(b) {
        if size(a) != size(b) {
            return Ok(false);
        }
        let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
        let a = values(a)?;
        let b = values(b)?;
        return any_match(a.iter().zip(&b), |(a, b)| Ok(!equal(a, b, depth)?))
            .map(|different| !different);
    }
    if is_collection(a) || is_collection(b) {
        return Ok(false);
    }
    Ok(match (normalized(a), normalized(b)) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Int(a), Value::Int(b)) => a == b,
        (Value::Float(a), Value::Float(b)) => a == b,
        (Value::Str(a), Value::Str(b)) | (Value::Html(a), Value::Html(b)) => a == b,
        (Value::Object(a), Value::Object(b)) => Rc::ptr_eq(&a, &b),
        _ => false,
    })
}

pub(super) fn any_match<T>(
    items: impl IntoIterator<Item = T>,
    mut test: impl FnMut(T) -> Result<bool>,
) -> Result<bool> {
    for item in items {
        if test(item)? {
            return Ok(true);
        }
    }
    Ok(false)
}

pub(super) fn compare(a: &Value<'_>, b: &Value<'_>, depth: usize) -> Result<Ordering> {
    fn unwrapped<'v, 'a>(mut value: &'v Value<'a>) -> &'v Value<'a> {
        while let Value::Object(object) = value {
            let Some(inner) = object.underlying() else {
                break;
            };
            value = inner;
        }
        value
    }

    let (a, b) = (unwrapped(a), unwrapped(b));
    if is_list(a) && is_list(b) {
        let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
        let a = values(a)?;
        let b = values(b)?;
        for (a, b) in a.iter().zip(&b) {
            let order = compare(a, b, depth)?;
            if order != Ordering::Equal {
                return Ok(order);
            }
        }
        return Ok(a.len().cmp(&b.len()));
    }
    let incompatible = || error("collection ordering requires values of the same ordered type");
    if is_collection(a) || is_collection(b) {
        return Err(incompatible());
    }
    match (normalized(a), normalized(b)) {
        (Value::Null, Value::Null) => Ok(Ordering::Equal),
        (Value::Int(a), Value::Int(b)) => Ok(a.cmp(&b)),
        (Value::Float(a), Value::Float(b)) => {
            a.partial_cmp(&b).ok_or_else(|| error("cannot order NaN"))
        }
        (Value::Bool(a), Value::Bool(b)) => Ok(a.cmp(&b)),
        (Value::Str(a), Value::Str(b)) | (Value::Html(a), Value::Html(b)) => Ok(a.cmp(&b)),
        _ => Err(incompatible()),
    }
}

pub(super) struct Args<'a, 'c>(pub(super) Vec<Arg<'a, 'c>>, pub(super) CallLimits);

impl<'a, 'c> Args<'a, 'c> {
    pub(super) fn count(&self, name: &str, min: usize, max: usize) -> Result<()> {
        if (min..=max).contains(&self.0.len()) {
            Ok(())
        } else {
            Err(error(format!(
                "{name} expects {min}..={max} arguments, got {}",
                self.0.len()
            )))
        }
    }

    pub(super) fn value(&self, i: usize) -> Result<Value<'a>> {
        match self.0.get(i) {
            Some(Arg::Value(v)) => Ok(normalized(v)),
            Some(Arg::Closure(_)) => Err(error("expected a value, received a closure")),
            None => Ok(Value::Null),
        }
    }

    pub(super) fn int(&self, i: usize, default: i64) -> Result<i64> {
        let value = self.value(i)?;
        if is_null(&value) {
            Ok(default)
        } else {
            integer(&value)
        }
    }

    pub(super) fn bool(&self, i: usize, default: bool) -> Result<bool> {
        let value = self.value(i)?;
        if is_null(&value) {
            Ok(default)
        } else {
            boolean(&value)
        }
    }

    pub(super) fn closure(&mut self, i: usize) -> Result<&mut dyn Callable<'a>> {
        match self.0.get_mut(i) {
            Some(Arg::Closure(call)) => Ok(&mut **call),
            _ => Err(error("expected a closure argument")),
        }
    }

    pub(super) fn has_closure(&self, i: usize) -> bool {
        matches!(self.0.get(i), Some(Arg::Closure(_)))
    }

    pub(super) fn call(&mut self, i: usize, args: &[Value<'a>]) -> Result<Value<'a>> {
        self.closure(i)?.call(args)
    }

    pub(super) fn default(&mut self, i: usize) -> Result<Value<'a>> {
        if self.has_closure(i) {
            self.call(i, &[])
        } else {
            self.value(i)
        }
    }

    pub(super) fn selector(&mut self, i: usize, (k, v): &Row<'a>) -> Result<Value<'a>> {
        if self.has_closure(i) {
            return self.call(i, &[v.clone(), k.clone()]);
        }
        let selector = self.value(i)?;
        if is_null(&selector) {
            Ok(normalized(v))
        } else {
            Ok(data_get(v, &key(&selector)?, self.1.data_depth())?.unwrap_or(Value::Null))
        }
    }
}

pub(super) fn json(value: &Value<'_>, depth: usize) -> Result<Json> {
    let child_depth = || depth.checked_sub(1).ok_or_else(data_depth_error);
    match value {
        Value::Json(Json::Array(values)) => {
            let depth = child_depth()?;
            Ok(Json::Array(
                values
                    .iter()
                    .map(|value| json(&Value::Json(value), depth))
                    .collect::<Result<_>>()?,
            ))
        }
        Value::Json(Json::Object(values)) => {
            let depth = child_depth()?;
            Ok(Json::Object(
                values
                    .iter()
                    .map(|(key, value)| Ok((key.clone(), json(&Value::Json(value), depth)?)))
                    .collect::<Result<_>>()?,
            ))
        }
        Value::Json(v) => Ok((*v).clone()),
        Value::Null => Ok(Json::Null),
        Value::Bool(v) => Ok(Json::Bool(*v)),
        Value::Int(v) => Ok(Json::from(*v)),
        Value::Float(v) => serde_json::Number::from_f64(*v)
            .map(Json::Number)
            .ok_or_else(|| error("cannot encode non-finite float")),
        Value::Str(v) | Value::Html(v) => Ok(Json::String(v.to_string())),
        Value::List(v) => {
            let depth = child_depth()?;
            Ok(Json::Array(
                v.iter().map(|v| json(v, depth)).collect::<Result<_>>()?,
            ))
        }
        Value::Map(v) => {
            let depth = child_depth()?;
            Ok(Json::Object(
                v.iter()
                    .map(|(k, v)| Ok((k.clone(), json(v, depth)?)))
                    .collect::<Result<_>>()?,
            ))
        }
        Value::Object(_) => Err(error("cannot serialize a render object as collection data")),
    }
}

pub(super) fn from_json<'a>(value: Json) -> Value<'a> {
    match value {
        Json::Null => Value::Null,
        Json::Bool(v) => Value::Bool(v),
        Json::Number(v) => v
            .as_i64()
            .map(Value::Int)
            .unwrap_or_else(|| Value::Float(v.as_f64().unwrap_or_default())),
        Json::String(v) => Value::string(v),
        Json::Array(v) => Value::List(v.into_iter().map(from_json).collect()),
        Json::Object(v) => Value::Map(v.into_iter().map(|(k, v)| (k, from_json(v))).collect()),
    }
}

pub(super) fn map<'a>() -> ValueMap<'a> {
    ValueMap::new()
}