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
//! The profile's functions from CEL's standard definitions and its strings extension (spec §8.2), each with its
//! documentation, its examples and its overloads.
#![allow(
clippy::unnecessary_wraps,
reason = "every implementation has an overload's signature, which can fail"
)]
use super::library::text;
use super::value::Value;
use super::{Functions, format, getters, optionals, patterns, strings, time};
use compmd_macros::library;
/// A function's implementation: it takes the render, for time zones, and the receiver, if any, then the arguments.
pub(crate) type Call = fn(&dyn Functions, &[Value]) -> Result<Value, String>;
/// A function of the profile from CEL. The `md.` functions come from outside.
#[library(prefix = "", call = Call)]
pub(crate) enum Function {
/// The length of a string, in characters, a list or a map.
///
/// ```cel
/// size("héllo") // 5
/// [1, 2, 3].size() // 3
/// ```
#[overload(fn(value: Sized) -> Int = size)]
#[overload(fn(self: Sized) -> Int = size)]
Size,
/// An int: a number without its fraction, a string read, a timestamp's seconds.
///
/// ```cel
/// int(3.7) // 3
/// int("42") // 42
/// ```
#[overload(fn(value: Int) -> Int = to_int)]
#[overload(fn(value: Uint) -> Int = to_int)]
#[overload(fn(value: Double) -> Int = to_int)]
#[overload(fn(value: String) -> Int = to_int)]
#[overload(fn(value: Timestamp) -> Int = to_int)]
Int,
/// A double from a number or a string.
///
/// ```cel
/// double("2.5") // 2.5
/// ```
#[overload(fn(value: Number) -> Double = to_double)]
#[overload(fn(value: String) -> Double = to_double)]
Double,
/// The value written as a string, as interpolation writes it.
///
/// ```cel
/// string(1e21) // "1e+21"
/// string(true) // "true"
/// ```
#[overload(fn(value: Number) -> String = to_string)]
#[overload(fn(value: String) -> String = to_string)]
#[overload(fn(value: Bool) -> String = to_string)]
#[overload(fn(value: Timestamp) -> String = to_string)]
#[overload(fn(value: Duration) -> String = to_string)]
String,
/// A timestamp from an RFC 3339 string.
///
/// ```cel
/// timestamp("2026-10-21T10:00:00Z") // "2026-10-21T10:00:00Z"
/// ```
#[overload(fn(text: String) -> Timestamp = to_timestamp)]
#[overload(fn(value: Timestamp) -> Timestamp = itself)]
Timestamp,
/// A duration from a string such as `1h30m`.
///
/// ```cel
/// duration("1h30m").getMinutes() // 90
/// ```
#[overload(fn(text: String) -> Duration = to_duration)]
#[overload(fn(value: Duration) -> Duration = itself)]
Duration,
/// The year, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getFullYear() // 2026
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::full_year)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::full_year)]
GetFullYear,
/// The month, from 0 for January, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getMonth() // 9
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::month)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::month)]
GetMonth,
/// The day of the month, from 1, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getDate() // 21
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::date)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::date)]
GetDate,
/// The day of the month, from 0, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getDayOfMonth() // 20
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::day_of_month)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::day_of_month)]
GetDayOfMonth,
/// The day of the week, from 0 for Sunday, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getDayOfWeek() // 3
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::day_of_week)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::day_of_week)]
GetDayOfWeek,
/// The day of the year, from 0, in `md.tz` or the time zone given.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getDayOfYear() // 293
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::day_of_year)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::day_of_year)]
GetDayOfYear,
/// A timestamp's hour, in `md.tz` or the time zone given, or a duration's whole hours.
///
/// ```cel
/// timestamp("2026-10-21T23:30:00Z").getHours("+02:00") // 1
/// duration("1h30m").getHours() // 1
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::hours)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::hours)]
#[overload(fn(self: Duration) -> Int = getters::duration_hours)]
GetHours,
/// A timestamp's minute, in `md.tz` or the time zone given, or a duration's whole minutes.
///
/// ```cel
/// duration("1h30m").getMinutes() // 90
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::minutes)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::minutes)]
#[overload(fn(self: Duration) -> Int = getters::duration_minutes)]
GetMinutes,
/// A timestamp's second, in `md.tz` or the time zone given, or a duration's whole seconds.
///
/// ```cel
/// timestamp("2026-10-21T10:00:05Z").getSeconds() // 5
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::seconds)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::seconds)]
#[overload(fn(self: Duration) -> Int = getters::duration_seconds)]
GetSeconds,
/// A timestamp's millisecond, in `md.tz` or the time zone given, or a duration's whole milliseconds.
///
/// ```cel
/// duration("1.5s").getMilliseconds() // 1500
/// ```
#[overload(fn(self: Timestamp) -> Int = getters::milliseconds)]
#[overload(fn(self: Timestamp, timeZone: String) -> Int = getters::milliseconds)]
#[overload(fn(self: Duration) -> Int = getters::duration_milliseconds)]
GetMilliseconds,
/// Whether the string holds the other.
///
/// ```cel
/// "rayplay".contains("play") // true
/// ```
#[overload(fn(self: String, substring: String) -> Bool = strings::contains)]
Contains,
/// Whether the string starts with the other.
///
/// ```cel
/// "rayplay".startsWith("ray") // true
/// ```
#[overload(fn(self: String, prefix: String) -> Bool = strings::starts_with)]
StartsWith,
/// Whether the string ends with the other.
///
/// ```cel
/// "rayplay".endsWith("play") // true
/// ```
#[overload(fn(self: String, suffix: String) -> Bool = strings::ends_with)]
EndsWith,
/// The character at a position, from 0.
///
/// ```cel
/// "héllo".charAt(1) // "é"
/// ```
#[overload(fn(self: String, index: Int) -> String = strings::char_at)]
#[counts]
CharAt,
/// The first position of a substring, or -1; from the position given.
///
/// ```cel
/// "banana".indexOf("an") // 1
/// "banana".indexOf("an", 2) // 3
/// ```
#[overload(fn(self: String, substring: String) -> Int = strings::index_of)]
#[overload(fn(self: String, substring: String, start: Int) -> Int = strings::index_of)]
#[counts]
IndexOf,
/// The last position of a substring, or -1; up to the position given.
///
/// ```cel
/// "banana".lastIndexOf("an") // 3
/// ```
#[overload(fn(self: String, substring: String) -> Int = strings::last_index_of)]
#[overload(fn(self: String, substring: String, start: Int) -> Int = strings::last_index_of)]
#[counts]
LastIndexOf,
/// The string with ASCII letters in lower case.
///
/// ```cel
/// "Hello".lowerAscii() // "hello"
/// ```
#[overload(fn(self: String) -> String = strings::lower_ascii)]
LowerAscii,
/// The string with ASCII letters in upper case.
///
/// ```cel
/// "Hello".upperAscii() // "HELLO"
/// ```
#[overload(fn(self: String) -> String = strings::upper_ascii)]
UpperAscii,
/// The string with a substring replaced, every time or as many times as given.
///
/// ```cel
/// "a-b-c".replace("-", " ") // "a b c"
/// "a-b-c".replace("-", " ", 1) // "a b-c"
/// ```
#[overload(fn(self: String, old: String, new: String) -> String = strings::replace, size = strings::replace_size)]
#[overload(fn(self: String, old: String, new: String, count: Int) -> String = strings::replace, size = strings::replace_size)]
#[counts]
Replace,
/// The parts between each separator; at most as many as given.
///
/// ```cel
/// "a,b,c".split(",") // ["a", "b", "c"]
/// ```
#[overload(fn(self: String, separator: String) -> Strings = strings::split, size = strings::split_size)]
#[overload(fn(self: String, separator: String, limit: Int) -> Strings = strings::split, size = strings::split_size)]
#[counts]
Split,
/// The characters from a position up to another, or to the end.
///
/// ```cel
/// "rayplay".substring(3) // "play"
/// "rayplay".substring(0, 3) // "ray"
/// ```
#[overload(fn(self: String, start: Int) -> String = strings::substring)]
#[overload(fn(self: String, start: Int, end: Int) -> String = strings::substring)]
#[counts]
Substring,
/// The string without white space at either end.
///
/// ```cel
/// " hi ".trim() // "hi"
/// ```
#[overload(fn(self: String) -> String = strings::trim)]
Trim,
/// Whether a part of the string matches the pattern, in RE2's syntax and written as a string literal.
///
/// ```cel
/// "v1.2".matches(r"^v\d+\.\d+$") // true
/// "release 1.2".matches(r"\d") // true
/// ```
#[overload(fn(self: String, pattern: String) -> Bool = patterns::matches)]
Matches,
/// The groups of the pattern, in RE2's syntax and written as a string literal, when the whole string matches
/// it: `""` for a group that took no part. None when it doesn't match.
///
/// ```cel
/// "2026-10".captures(r"(\d+)-(\d+)").value() // ["2026", "10"]
/// "v2".captures(r"v(\d+)(\.\d+)?").value() // ["2", ""]
/// "October".captures(r"(\d+)").hasValue() // false
/// ```
#[overload(fn(self: String, pattern: String) -> OptionalStrings = patterns::captures, size = patterns::captures_size)]
Captures,
/// The strings of the list joined, with the separator given.
///
/// ```cel
/// ["a", "b"].join(", ") // "a, b"
/// ```
#[overload(fn(self: Strings) -> String = strings::join, size = strings::join_size)]
#[overload(fn(self: Strings, separator: String) -> String = strings::join, size = strings::join_size)]
Join,
/// The string with each verb written with its value from the list, locale-free: `%s` a value as interpolation
/// writes it, `%d` an int, `%f` and `%.Nf` a number with 6 or `N` decimals, `%%` a `%`. A width pads with spaces
/// before, or with zeros after a `0` for `%d` and `%f`.
///
/// ```cel
/// "%.1f %s".format([7.5, "mi"]) // "7.5 mi"
/// "%d:%02d".format([1, 5]) // "1:05"
/// "%5.1f".format([7.5]) // " 7.5"
/// ```
#[overload(fn(self: String, values: List) -> String = format::format, size = format::format_size)]
Format,
/// Whether the optional has a value.
///
/// ```cel
/// optional.of(1).hasValue() // true
/// [1, 2][?5].hasValue() // false
/// ```
#[overload(fn(self: Optional) -> Bool = optionals::has_value)]
HasValue,
/// The optional's value; an error without one.
///
/// ```cel
/// {"a": 1}.?a.value() // 1
/// ```
#[overload(fn(self: Optional) -> Unwrapped(0) = optionals::value)]
Value,
/// The optional's value, or the value given without one.
///
/// ```cel
/// {"a": 1}.?b.orValue(0) // 0
/// ```
#[overload(fn(self: Optional, otherwise: Any) -> UnwrappedOr(0) = optionals::or_value)]
OrValue,
/// The optional when it has a value, the other optional otherwise.
///
/// ```cel
/// optional.none().or(optional.of(2)).value() // 2
/// ```
#[overload(fn(self: Optional, otherwise: Optional) -> Same(0) = optionals::or)]
Or,
}
/// CEL functions the profile leaves out, named as such when used.
pub(crate) const LEFT_OUT: [&str; 6] = ["uint", "bytes", "type", "dyn", "quote", "reverse"];
fn size(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let n = match args.first() {
Some(Value::String(s)) => s.chars().count(),
Some(Value::List(items)) => items.len(),
Some(Value::Map(entries)) => entries.len(),
_ => 0,
};
Ok(Value::Int(i64::try_from(n).unwrap_or(i64::MAX)))
}
fn itself(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(args.first().cloned().unwrap_or(Value::Null))
}
#[allow(
clippy::cast_possible_truncation,
reason = "the double is in range, and CEL truncates it"
)]
fn to_int(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let Some(value) = args.first() else {
return Ok(Value::Null);
};
let too_big = || format!("{} doesn't fit an int", value.text());
match value {
Value::Uint(u) => i64::try_from(*u).map(Value::Int).map_err(|_| too_big()),
// -2^63 fits; 2^63 doesn't.
Value::Double(d)
if (-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(d) =>
{
Ok(Value::Int(d.trunc() as i64))
}
Value::Double(_) => Err(too_big()),
Value::String(s) => s
.parse()
.map(Value::Int)
.map_err(|_| format!("'{s}' is not an int")),
Value::Timestamp(t) => Ok(Value::Int(
i64::try_from(t.div_euclid(time::NANOS)).unwrap_or_default(),
)),
other => Ok(other.clone()),
}
}
#[allow(
clippy::cast_precision_loss,
reason = "CEL converts an integer to the nearest double"
)]
fn to_double(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
match args.first() {
Some(Value::Int(i)) => Ok(Value::Double(*i as f64)),
Some(Value::Uint(u)) => Ok(Value::Double(*u as f64)),
Some(Value::String(s)) => s
.parse()
.map(Value::Double)
.map_err(|_| format!("'{s}' is not a double")),
other => Ok(other.cloned().unwrap_or(Value::Null)),
}
}
fn to_string(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(Value::string(
&args.first().map(Value::text).unwrap_or_default(),
))
}
fn to_timestamp(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let s = text(args, 0);
time::parse_timestamp(s)
.map(Value::Timestamp)
.ok_or_else(|| format!("'{s}' is not an RFC 3339 timestamp in CEL's range"))
}
fn to_duration(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let s = text(args, 0);
time::parse_duration(s)
.map(Value::Duration)
.ok_or_else(|| format!("'{s}' is not a duration such as '1h30m'"))
}