gotmpl 0.4.0

A Rust reimplementation of Go's text/template library
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
438
439
440
441
442
443
444
445
446
//! Built-in template functions, matching Go's `text/template` builtins.
//!
//! In Go, template functions live in a `FuncMap` and are called via
//! reflection. Here they are boxed closures with the signature [`ValueFunc`].
//! Built-ins are registered automatically when creating a
//! [`Template`](crate::Template); custom functions can be added via
//! [`Template::func`](crate::Template::func).
//!
//! # Built-in function reference
//!
//! | Category | Functions |
//! |----------|-----------|
//! | Comparison | `eq`, `ne`, `lt`, `le`, `gt`, `ge` |
//! | Logic | `and`, `or`, `not` |
//! | Output | `print`, `printf`, `println` |
//! | Data | `len`, `index`, `slice`, `call` |
//! | Escaping | `html`, `js`, `urlquery` |
//!
//! # Escape-function security notes
//!
//! The escape builtins match Go's `text/template` exactly, which is **not**
//! enough for all HTML/JS contexts:
//!
//! - `html` does **not** escape backticks and is only safe inside
//!   double-quoted attribute values or text nodes. Never use it in unquoted
//!   attributes, `<script>` blocks, or inline event handlers.
//! - `js` escapes the JS string-literal metacharacters plus `<`, `>`, `&`,
//!   `=`, control chars, and U+2028 / U+2029 — but produces output suitable
//!   for embedding inside a JS string literal, not arbitrary JS contexts.
//! - `urlquery` percent-encodes for query strings (form-encoded: space → `+`)
//!   and is not a replacement for full URL-construction logic when building
//!   paths.
//!
//! For context-aware escaping use a dedicated `html/template`-style crate.

use alloc::borrow::Cow;
use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use core::cmp::Ordering;
use core::fmt::Write;

use crate::error::{Result, TemplateError};
use crate::go;
use crate::value::{Value, ValueFunc};

/// Returns a [`BTreeMap`] containing all built-in template functions.
///
/// Called automatically by [`Template::new`](crate::Template::new); extend the
/// result with [`Template::func`](crate::Template::func) for custom functions.
pub fn builtins() -> BTreeMap<String, ValueFunc> {
    let mut m: BTreeMap<String, ValueFunc> = BTreeMap::new();

    // Comparison operators
    // Go's eq can take 2+ args: eq x y z means x==y || x==z

    m.insert(
        "eq".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("eq", args, 2)?;
            let first = &args[0];
            for arg in &args[1..] {
                if compare_eq(first, arg)? {
                    return Ok(Value::Bool(true));
                }
            }
            Ok(Value::Bool(false))
        }),
    );

    m.insert(
        "ne".into(),
        Arc::new(|args: &[Value]| {
            check_args("ne", args, 2)?;
            Ok(Value::Bool(!compare_eq(&args[0], &args[1])?))
        }),
    );

    m.insert(
        "lt".into(),
        Arc::new(|args: &[Value]| {
            check_args("lt", args, 2)?;
            Ok(Value::Bool(
                compare_order(&args[0], &args[1])? == Ordering::Less,
            ))
        }),
    );

    m.insert(
        "le".into(),
        Arc::new(|args: &[Value]| {
            check_args("le", args, 2)?;
            let ord = compare_order(&args[0], &args[1])?;
            Ok(Value::Bool(ord == Ordering::Less || ord == Ordering::Equal))
        }),
    );

    m.insert(
        "gt".into(),
        Arc::new(|args: &[Value]| {
            check_args("gt", args, 2)?;
            Ok(Value::Bool(
                compare_order(&args[0], &args[1])? == Ordering::Greater,
            ))
        }),
    );

    m.insert(
        "ge".into(),
        Arc::new(|args: &[Value]| {
            check_args("ge", args, 2)?;
            let ord = compare_order(&args[0], &args[1])?;
            Ok(Value::Bool(
                ord == Ordering::Greater || ord == Ordering::Equal,
            ))
        }),
    );

    // Logic
    // and: returns first falsy arg, or last arg if all truthy
    // or:  returns first truthy arg, or last arg if all falsy
    //
    // NOTE: and/or are special-cased in the executor for short-circuit
    // evaluation. These implementations are kept as fallbacks but the
    // executor calls them with pre-evaluated args only when not
    // short-circuiting (which shouldn't happen in normal flow).

    m.insert(
        "and".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("and", args, 1)?;
            for arg in args {
                if !arg.is_truthy() {
                    return Ok(arg.clone());
                }
            }
            Ok(args.last().cloned().unwrap_or(Value::Nil))
        }),
    );

    m.insert(
        "or".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("or", args, 1)?;
            for arg in args {
                if arg.is_truthy() {
                    return Ok(arg.clone());
                }
            }
            Ok(args.last().cloned().unwrap_or(Value::Nil))
        }),
    );

    m.insert(
        "not".into(),
        Arc::new(|args: &[Value]| {
            check_args("not", args, 1)?;
            Ok(Value::Bool(!args[0].is_truthy()))
        }),
    );

    // Output formatting
    m.insert(
        "print".into(),
        Arc::new(|args: &[Value]| {
            let mut result = String::new();
            for (i, arg) in args.iter().enumerate() {
                if i > 0 && go::needs_space(&args[i - 1], arg) {
                    result.push(' ');
                }
                write!(result, "{}", arg).ok();
            }
            Ok(Value::String(Arc::from(result)))
        }),
    );

    m.insert(
        "println".into(),
        Arc::new(|args: &[Value]| {
            let mut result = String::new();
            for (i, arg) in args.iter().enumerate() {
                if i > 0 {
                    result.push(' ');
                }
                write!(result, "{}", arg).ok();
            }
            result.push('\n');
            Ok(Value::String(Arc::from(result)))
        }),
    );

    m.insert(
        "printf".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("printf", args, 1)?;
            let fmt_str: &str = match &args[0] {
                Value::String(s) => s,
                other => {
                    return Err(TemplateError::Exec(format!(
                        "printf: first arg must be string, got {}",
                        other
                    )));
                }
            };
            let result = go::sprintf(fmt_str, &args[1..])?;
            Ok(Value::String(Arc::from(result.into_boxed_str())))
        }),
    );

    // Data access
    m.insert(
        "len".into(),
        Arc::new(|args: &[Value]| {
            check_args("len", args, 1)?;
            match args[0].len() {
                Some(n) => Ok(Value::Int(n as i64)),
                None => Err(TemplateError::Exec(format!(
                    "len: cannot take length of {}",
                    args[0]
                ))),
            }
        }),
    );

    m.insert(
        "index".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("index", args, 2)?;
            let mut val = args[0].clone();
            for idx in &args[1..] {
                val = val.index(idx)?;
            }
            Ok(val)
        }),
    );

    // slice: Go allows 1-4 args total:
    // slice x, slice x i, slice x i j, slice x i j k
    m.insert(
        "slice".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("slice", args, 1)?;
            if args.len() > 4 {
                return Err(TemplateError::Exec(format!(
                    "wrong number of args for slice: want 1-4 got {}",
                    args.len()
                )));
            }

            let v = &args[0];
            match args.len() {
                1 => v.slice(None, None),
                2 => {
                    let start = parse_slice_index(&args[1])?;
                    v.slice(Some(start), None)
                }
                3 => {
                    let start = parse_slice_index(&args[1])?;
                    let end = parse_slice_index(&args[2])?;
                    v.slice(Some(start), Some(end))
                }
                4 => {
                    // 3-index slice. We only support this for lists (like slices),
                    // and we validate i <= j <= k <= len.
                    let start = parse_slice_index(&args[1])?;
                    let end = parse_slice_index(&args[2])?;
                    let max = parse_slice_index(&args[3])?;
                    match v {
                        Value::List(list) => {
                            let len = list.len() as i64;
                            if start < 0 || end < 0 || max < 0 {
                                return Err(TemplateError::Exec(format!(
                                    "slice: index out of range [{}:{}:{}]",
                                    start, end, max
                                )));
                            }
                            if start > end {
                                return Err(TemplateError::Exec(format!(
                                    "slice: invalid slice index: {} > {}",
                                    start, end
                                )));
                            }
                            if end > max {
                                return Err(TemplateError::Exec(format!(
                                    "slice: invalid slice index: {} > {}",
                                    end, max
                                )));
                            }
                            if max > len {
                                return Err(TemplateError::Exec(format!(
                                    "slice: index out of range [{}:{}:{}] with length {}",
                                    start, end, max, len
                                )));
                            }
                            v.slice(Some(start), Some(end))
                        }
                        Value::String(_) => Err(TemplateError::Exec(
                            "slice: cannot 3-index slice a string".into(),
                        )),
                        _ => Err(TemplateError::Exec(format!(
                            "slice: cannot slice type {}",
                            v.type_name()
                        ))),
                    }
                }
                #[allow(
                    clippy::unreachable,
                    reason = "args.len() is in 1..=4: bounded by check_min_args and the `> 4` bailout above"
                )]
                _ => unreachable!(),
            }
        }),
    );

    // call: invoke a function-typed value
    m.insert(
        "call".into(),
        Arc::new(|args: &[Value]| {
            check_min_args("call", args, 1)?;
            match &args[0] {
                Value::Function(f) => f(&args[1..]),
                Value::Nil => Err(TemplateError::Exec("call of nil".into())),
                other => Err(TemplateError::Exec(format!(
                    "call: non-function value of type {}",
                    other.type_name()
                ))),
            }
        }),
    );

    // HTML/JS/URL escaping
    m.insert(
        "html".into(),
        Arc::new(|args: &[Value]| {
            check_args("html", args, 1)?;
            let s = stringify_for_escaper(&args[0]);
            Ok(Value::String(Arc::from(go::html_escape(&s))))
        }),
    );

    m.insert(
        "js".into(),
        Arc::new(|args: &[Value]| {
            check_args("js", args, 1)?;
            let s = stringify_for_escaper(&args[0]);
            Ok(Value::String(Arc::from(go::js_escape(&s))))
        }),
    );

    m.insert(
        "urlquery".into(),
        Arc::new(|args: &[Value]| {
            check_args("urlquery", args, 1)?;
            let s = stringify_for_escaper(&args[0]);
            Ok(Value::String(Arc::from(go::url_encode(&s))))
        }),
    );

    m
}

/// Stringify a value the way Go's `evalArgs` does for `html` / `js` /
/// `urlquery`: nil renders as `<no value>` (the template engine's missing-
/// value sentinel), not `<nil>` (which is what `fmt.Sprint(nil)` gives).
///
/// Returns `Cow` so the `Value::String` case — the typical input — borrows
/// instead of cloning.
fn stringify_for_escaper(v: &Value) -> Cow<'_, str> {
    match v {
        Value::Nil => Cow::Borrowed("<no value>"),
        Value::String(s) => Cow::Borrowed(s.as_ref()),
        _ => Cow::Owned(format!("{}", v)),
    }
}

// Argument validation helpers
fn check_args(name: &str, args: &[Value], expected: usize) -> Result<()> {
    if args.len() != expected {
        return Err(TemplateError::ArgCount {
            name: name.to_string(),
            expected,
            got: args.len(),
        });
    }
    Ok(())
}

fn check_min_args(name: &str, args: &[Value], min: usize) -> Result<()> {
    if args.len() < min {
        return Err(TemplateError::ArgCount {
            name: name.to_string(),
            expected: min,
            got: args.len(),
        });
    }
    Ok(())
}

fn compare_eq(left: &Value, right: &Value) -> Result<bool> {
    match (left, right) {
        (Value::Nil, Value::Nil) => Ok(true),
        (Value::Nil, _) | (_, Value::Nil) => Ok(false),
        (Value::Bool(a), Value::Bool(b)) => Ok(a == b),
        (Value::Int(a), Value::Int(b)) => Ok(a == b),
        (Value::Float(a), Value::Float(b)) => Ok(a == b),
        (Value::String(a), Value::String(b)) => Ok(a == b),
        (Value::List(_), Value::List(_))
        | (Value::Map(_), Value::Map(_))
        | (Value::Function(_), Value::Function(_)) => Err(TemplateError::Exec(format!(
            "non-comparable type {}",
            left.type_name()
        ))),
        _ => Err(TemplateError::Exec(format!(
            "incompatible types for comparison: {} and {}",
            left.type_name(),
            right.type_name()
        ))),
    }
}

fn compare_order(left: &Value, right: &Value) -> Result<Ordering> {
    match (left, right) {
        (Value::Int(a), Value::Int(b)) => Ok(a.cmp(b)),
        (Value::Float(a), Value::Float(b)) => a
            .partial_cmp(b)
            .ok_or_else(|| TemplateError::Exec("invalid type for comparison".into())),
        (Value::String(a), Value::String(b)) => Ok(a.cmp(b)),
        _ if left.type_name() != right.type_name() => Err(TemplateError::Exec(format!(
            "incompatible types for comparison: {} and {}",
            left.type_name(),
            right.type_name()
        ))),
        _ => Err(TemplateError::Exec("invalid type for comparison".into())),
    }
}

fn parse_slice_index(arg: &Value) -> Result<i64> {
    match arg {
        Value::Int(n) => Ok(*n),
        _ => Err(TemplateError::Exec(format!(
            "slice: index must be integer, got {}",
            arg.type_name()
        ))),
    }
}