run-rs 0.2.16

Run a subset of Rust as an interpreted script
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Engine neutral method cores, written once and materialized by both engines.
//!
//! The fast engine and the parallel engine used to carry their own copy of
//! every scalar method, and the copies drifted. A core here works on plain
//! Rust types and answers through a small output enum, so each engine only
//! adapts arguments in and values out. The coverage harvest reads this file
//! once as `Engine::Both`, so a method added here reaches both engines and
//! both tables in the same commit.
//!
//! What stays engine side: anything lazy or stateful. The fast engine's
//! iterator forms of `chars`, `lines`, `bytes`, and `split_whitespace` cannot
//! be expressed as a finished value, and containers live behind different
//! cell types per engine.

use std::cmp::Ordering;

use anyhow::{Result, bail};

use super::bytecode::ScalarTy;
use super::numeric::IntWidth;

/// Engine neutral view of a method's arguments. Each engine adapts its own
/// value slice; the cores monomorphize over this, so the view costs nothing.
pub(super) trait Args {
    /// The argument rendered as text, what `Display` would print. Missing
    /// arguments render empty, matching how both engines behaved.
    fn text(&self, i: usize) -> String;
    fn int(&self, i: usize) -> Option<i64>;
    /// An integer, or an integer view of a float argument.
    fn float(&self, i: usize) -> Option<f64>;
    /// The chars of a `['-', '_']` style pattern array argument, so a char
    /// set splits on any of its members rather than the rendered text.
    fn pattern_chars(&self, i: usize) -> Option<Vec<char>>;
}

fn int_arg(args: &impl Args, i: usize) -> Result<i64> {
    match args.int(i) {
        Some(n) => Ok(n),
        None => bail!("expected an integer argument"),
    }
}

fn float_arg(args: &impl Args, i: usize) -> Result<f64> {
    match args.float(i) {
        Some(f) => Ok(f),
        None => bail!("expected a float argument"),
    }
}

// -- numbers ---------------------------------------------------------------

#[derive(Clone, Copy)]
pub(super) enum Num {
    Int(i64),
    Float(f64),
}

/// What a numeric method produced, materialized by each engine.
pub(super) enum NumOut {
    Int(i64),
    Float(f64),
    Bool(bool),
    SomeInt(i64),
    SomeFloat(f64),
    Nothing,
    Ordering(Ordering),
    SomeOrdering(Ordering),
}

pub(super) fn num_core(recv: Num, name: &str, args: &impl Args) -> Result<Option<NumOut>> {
    use Num::{Float, Int};
    use NumOut as O;
    let as_f = || match recv {
        Int(i) => i as f64,
        Float(f) => f,
    };
    Ok(Some(match (recv, name) {
        (Int(i), "as_i64" | "as_u64" | "as_i128" | "as_usize") => O::SomeInt(i),
        // serde_json keeps every json float as f64 and its integer accessors
        // answer None on it, even for a whole value like 5.0.
        (Float(_), "as_i64" | "as_u64" | "as_i128" | "as_usize") => O::Nothing,
        (_, "as_f64") => O::SomeFloat(as_f()),
        // A number is not these serde types, so the accessor is None.
        (_, "as_str" | "as_bool" | "as_array" | "as_array_mut" | "as_object" | "as_object_mut") => {
            O::Nothing
        }
        (Int(i), "abs") => O::Int(i.abs()),
        (Float(f), "abs") => O::Float(f.abs()),
        (Int(i), "pow") => O::Int(i.pow(int_arg(args, 0)? as u32)),
        (Float(f), "powi") => O::Float(f.powi(int_arg(args, 0)? as i32)),
        (Float(f), "powf") => O::Float(f.powf(float_arg(args, 0)?)),
        (Float(f), "sqrt") => O::Float(f.sqrt()),
        (Float(f), "floor") => O::Float(f.floor()),
        (Float(f), "trunc") => O::Float(f.trunc()),
        // Float methods on an int receiver: the untyped `parse` guesses a
        // whole float like "160" into an int, and the annotation that made it
        // f64 in real Rust is erased at runtime. Rounding is identity there,
        // and the rest compute through the float view.
        (Int(i), "trunc" | "floor" | "ceil" | "round") => O::Int(i),
        (Int(_), "sqrt") => O::Float(as_f().sqrt()),
        (Int(_), "powi") => O::Float(as_f().powi(int_arg(args, 0)? as i32)),
        (Int(_), "powf") => O::Float(as_f().powf(float_arg(args, 0)?)),
        (Int(i), "is_sign_positive") => O::Bool(i >= 0),
        (Float(f), "ceil") => O::Float(f.ceil()),
        (Float(f), "round") => O::Float(f.round()),
        (Float(f), "is_sign_positive") => O::Bool(f.is_sign_positive()),
        (Int(a), "min") => O::Int(a.min(int_arg(args, 0)?)),
        (Int(a), "max") => O::Int(a.max(int_arg(args, 0)?)),
        (Int(a), "clamp") => O::Int(a.clamp(int_arg(args, 0)?, int_arg(args, 1)?)),
        (Float(a), "clamp") => O::Float(a.clamp(float_arg(args, 0)?, float_arg(args, 1)?)),
        (Float(a), "min") => O::Float(a.min(float_arg(args, 0)?)),
        (Float(a), "max") => O::Float(a.max(float_arg(args, 0)?)),
        (Int(a), "is_multiple_of") => O::Bool(a % int_arg(args, 0)? == 0),
        (Int(a), "saturating_sub") => O::Int(a.saturating_sub(int_arg(args, 0)?)),
        (Int(a), "saturating_add") => O::Int(a.saturating_add(int_arg(args, 0)?)),
        (Int(a), "saturating_mul") => O::Int(a.saturating_mul(int_arg(args, 0)?)),
        (Int(a), "cmp") => O::Ordering(a.cmp(&int_arg(args, 0)?)),
        (_, "partial_cmp") => O::SomeOrdering(
            as_f()
                .partial_cmp(&float_arg(args, 0)?)
                .unwrap_or(Ordering::Equal),
        ),
        _ => return Ok(None),
    }))
}

// -- chars -----------------------------------------------------------------

/// The result of a `char` method, in a form either engine can turn into its
/// own value type. Keeps the classification table in one place.
pub(super) enum CharOut {
    Bool(bool),
    Char(char),
    Str(String),
}

/// The `char` classification and conversion methods, shared by both engines so
/// a script sees the same set whichever one runs it.
pub(super) fn char_method(ch: char, name: &str) -> Option<CharOut> {
    let b = |v: bool| Some(CharOut::Bool(v));
    match name {
        "is_ascii_digit" => b(ch.is_ascii_digit()),
        "is_ascii_alphabetic" => b(ch.is_ascii_alphabetic()),
        "is_ascii_alphanumeric" => b(ch.is_ascii_alphanumeric()),
        "is_ascii_uppercase" => b(ch.is_ascii_uppercase()),
        "is_ascii_lowercase" => b(ch.is_ascii_lowercase()),
        "is_ascii_whitespace" => b(ch.is_ascii_whitespace()),
        "is_ascii_punctuation" => b(ch.is_ascii_punctuation()),
        "is_ascii_hexdigit" => b(ch.is_ascii_hexdigit()),
        "is_ascii" => b(ch.is_ascii()),
        "is_alphabetic" => b(ch.is_alphabetic()),
        "is_alphanumeric" => b(ch.is_alphanumeric()),
        "is_numeric" => b(ch.is_numeric()),
        "is_whitespace" => b(ch.is_whitespace()),
        "is_uppercase" => b(ch.is_uppercase()),
        "is_lowercase" => b(ch.is_lowercase()),
        "to_ascii_uppercase" => Some(CharOut::Char(ch.to_ascii_uppercase())),
        "to_ascii_lowercase" => Some(CharOut::Char(ch.to_ascii_lowercase())),
        // These yield an iterator in real Rust, but a script only ever renders
        // or collects it, so the string it would produce is handed back.
        "to_uppercase" => Some(CharOut::Str(ch.to_uppercase().to_string())),
        "to_lowercase" => Some(CharOut::Str(ch.to_lowercase().to_string())),
        _ => None,
    }
}

// -- strings ---------------------------------------------------------------

/// What a string method produced, materialized by each engine. `Keep` and
/// `OkKeep` hand the receiver back so both engines answer with a refcount
/// bump, never a copy.
pub(super) enum StrOut {
    Bool(bool),
    Int(i64),
    Owned(String),
    Keep,
    OkKeep,
    Strs(Vec<String>),
    CharIdx(Vec<(i64, char)>),
    Ints(Vec<i64>),
    OptOwned(Option<String>),
    OptInt(Option<i64>),
    OptPair(Option<(String, String)>),
    Ordering(Ordering),
}

/// The untyped `parse` guess: int first, then float, then bool.
pub(super) fn str_core(s: &str, name: &str, args: &impl Args) -> Result<Option<StrOut>> {
    use StrOut as O;
    let a = |i: usize| args.text(i);
    Ok(Some(match name {
        "len" => O::Int(s.len() as i64),
        "is_empty" => O::Bool(s.is_empty()),
        "count" => O::Int(s.chars().count() as i64),
        "contains" => O::Bool(s.contains(&a(0))),
        "eq_ignore_ascii_case" => O::Bool(s.eq_ignore_ascii_case(&a(0))),
        "starts_with" => O::Bool(s.starts_with(&a(0))),
        "ends_with" => O::Bool(s.ends_with(&a(0))),
        "trim" => O::Owned(s.trim().to_string()),
        "trim_start" => O::Owned(s.trim_start().to_string()),
        "trim_end" => O::Owned(s.trim_end().to_string()),
        "to_uppercase" => O::Owned(s.to_uppercase()),
        "to_lowercase" => O::Owned(s.to_lowercase()),
        // The ascii variants leave non-ascii characters alone, they are not
        // aliases of the unicode ones.
        "to_ascii_uppercase" => O::Owned(s.to_ascii_uppercase()),
        "to_ascii_lowercase" => O::Owned(s.to_ascii_lowercase()),
        // A char-set pattern like `[':', '.']` replaces any of its members, matching real Rust. Without
        // this the array renders as text and matches nothing, silently leaving the string unchanged.
        "replace" => match args.pattern_chars(0) {
            Some(cs) => O::Owned(s.replace(cs.as_slice(), &a(1))),
            None => O::Owned(s.replace(&a(0), &a(1))),
        },
        "replacen" => match args.pattern_chars(0) {
            Some(cs) => O::Owned(s.replacen(cs.as_slice(), &a(1), int_arg(args, 2)? as usize)),
            None => O::Owned(s.replacen(&a(0), &a(1), int_arg(args, 2)? as usize)),
        },
        "repeat" => {
            let n = args
                .int(0)
                .and_then(|n| usize::try_from(n).ok())
                .unwrap_or(0);
            O::Owned(s.repeat(n))
        }
        // String::as_str gives the string back. serde_json::Value::as_str
        // gives an Option, and a json string is a plain Str here, so unwrap
        // and expect on a string are identity to keep serde chains working.
        "to_owned" | "trim_string" | "as_str" | "as_string" | "unwrap" | "expect" => O::Keep,
        "unwrap_or" | "unwrap_or_else" | "unwrap_or_default" => O::Keep,
        // A String or a Cow that already owns its data, into_owned is self.
        "into_owned" | "into_string" => O::Keep,
        // `Option::context` returns a Result, so the pre-unwrapped string has
        // to come back wrapped or a following `?` would have nothing to unwrap.
        "context" | "with_context" => O::OkKeep,
        "is_some" => O::Bool(true),
        "is_none" => O::Bool(false),
        "as_bytes" | "into_bytes" => O::Ints(s.bytes().map(i64::from).collect()),
        // The utf-16 code units as an eager list of ints, mirroring `bytes`.
        "encode_utf16" => O::Ints(s.encode_utf16().map(i64::from).collect()),
        "strip_prefix" => O::OptOwned(s.strip_prefix(&a(0)).map(str::to_string)),
        "strip_suffix" => O::OptOwned(s.strip_suffix(&a(0)).map(str::to_string)),
        // Byte offsets, same as the real std, and slicing is byte based too,
        // so `&s[..s.find(x).unwrap()]` behaves right.
        "find" => O::OptInt(s.find(&a(0)).map(|i| i as i64)),
        "rfind" => O::OptInt(s.rfind(&a(0)).map(|i| i as i64)),
        "split_once" => O::OptPair(
            s.split_once(&a(0))
                .map(|(x, y)| (x.to_string(), y.to_string())),
        ),
        "rsplit_once" => O::OptPair(
            s.rsplit_once(&a(0))
                .map(|(x, y)| (x.to_string(), y.to_string())),
        ),
        // A char array like `['-', '_']` splits on any of its members, which
        // a plain string pattern would only match as the literal sequence.
        "split" => match args.pattern_chars(0) {
            Some(chars) => O::Strs(
                s.split(|c: char| chars.contains(&c))
                    .map(str::to_string)
                    .collect(),
            ),
            None => O::Strs(s.split(&a(0)).map(str::to_string).collect()),
        },
        "rsplit" => O::Strs(s.rsplit(&a(0)).map(str::to_string).collect()),
        "splitn" => {
            let n = int_arg(args, 0)? as usize;
            O::Strs(s.splitn(n, &a(1)).map(str::to_string).collect())
        }
        "rsplitn" => {
            let n = int_arg(args, 0)? as usize;
            O::Strs(s.rsplitn(n, &a(1)).map(str::to_string).collect())
        }
        "matches" => O::Strs(s.matches(&a(0)).map(str::to_string).collect()),
        "char_indices" => O::CharIdx(s.char_indices().map(|(i, c)| (i as i64, c)).collect()),
        "trim_matches" | "trim_start_matches" | "trim_end_matches" => {
            let pat = a(0);
            let out = match name {
                "trim_start_matches" => s.trim_start_matches(&pat),
                "trim_end_matches" => s.trim_end_matches(&pat),
                // trim_matches only takes chars in real Rust.
                _ => match args.pattern_chars(0) {
                    Some(chars) => s.trim_matches(|c: char| chars.contains(&c)),
                    None => s.trim_matches(pat.chars().next().unwrap_or(' ')),
                },
            };
            O::Owned(out.to_string())
        }
        "cmp" => O::Ordering(s.cmp(a(0).as_str())),
        // `parse` without a turbofish is answered by the engines through
        // `parse_core`, which is the only place that sees the target type.
        _ => return Ok(None),
    }))
}

/// What `str::parse` produced, before either engine wraps it in an `Ok`.
pub(super) enum Parsed {
    Int(i128, IntWidth),
    F32(f32),
    F64(f64),
    Bool(bool),
    Char(char),
    Str(String),
    Fail(String),
}

/// `str::parse`, honoring the target type when the call wrote one down.
///
/// Real Rust decides this entirely by the target: the text must be the whole
/// value with no surrounding whitespace, and an integer target rejects
/// anything outside its own range. Guessing instead made `"300".parse::<u8>()`
/// an `Ok(300)` and `" 5 ".parse::<i64>()` an `Ok(5)`, both of which real Rust
/// rejects. Without a turbofish there is no type to honor, so the old guess
/// stays, which is what a plain `let n: u8 = s.parse()?` still lands on.
pub(super) fn parse_core(text: &str, target: Option<&ScalarTy>) -> Parsed {
    let fail = || Parsed::Fail(format!("cannot parse `{text}`"));
    let Some(target) = target else {
        let trimmed = text.trim();
        return if let Ok(value) = trimmed.parse::<i64>() {
            Parsed::Int(i128::from(value), IntWidth::I64)
        } else if let Ok(value) = trimmed.parse::<f64>() {
            Parsed::F64(value)
        } else if let Ok(value) = trimmed.parse::<bool>() {
            Parsed::Bool(value)
        } else {
            Parsed::Fail(format!("cannot parse `{trimmed}`"))
        };
    };
    match target {
        ScalarTy::Int(width) => match text.parse::<i128>() {
            Ok(value) if value >= width.min() && value <= width.max() => Parsed::Int(value, *width),
            _ => fail(),
        },
        ScalarTy::F32 => text.parse::<f32>().map_or_else(|_| fail(), Parsed::F32),
        ScalarTy::F64 => text.parse::<f64>().map_or_else(|_| fail(), Parsed::F64),
        ScalarTy::Bool => text.parse::<bool>().map_or_else(|_| fail(), Parsed::Bool),
        ScalarTy::Char => text.parse::<char>().map_or_else(|_| fail(), Parsed::Char),
        ScalarTy::Str => Parsed::Str(text.to_string()),
        // No container implements `FromStr`, so these never name a parse
        // target. They exist only to describe a `Default`.
        ScalarTy::Opt(_) | ScalarTy::List(_) | ScalarTy::Other => fail(),
    }
}

// -- regex -----------------------------------------------------------------

/// What a `Regex` method produced. Spans index into the source string the
/// engine already holds, so each engine materializes its own match handles.
pub(super) enum RegexOut {
    Bool(bool),
    Text(String),
    /// The engine answers with its shared pattern handle.
    Pattern,
    /// `find`: the first match's span, if any.
    OptSpan(Option<(usize, usize)>),
    /// `captures`: per group, its span when the group matched.
    OptGroups(Option<Vec<Option<(usize, usize)>>>),
    /// `split`: the pieces as owned strings.
    Pieces(Vec<String>),
}

/// The eager `Regex` methods. The `find_iter` and `captures_iter` forms stay
/// engine side, the fast engine streams them lazily and the parallel engine
/// collects them.
pub(super) fn regex_core(
    re: &regex::Regex,
    name: &str,
    source: &str,
    replacement: &dyn Fn() -> String,
) -> Option<RegexOut> {
    use RegexOut as O;
    Some(match name {
        "is_match" => O::Bool(re.is_match(source)),
        "find" => O::OptSpan(re.find(source).map(|m| (m.start(), m.end()))),
        "captures" => O::OptGroups(re.captures(source).map(|c| {
            (0..c.len())
                .map(|i| c.get(i).map(|g| (g.start(), g.end())))
                .collect()
        })),
        "replace" => O::Text(re.replacen(source, 1, replacement().as_str()).into_owned()),
        "replace_all" => O::Text(re.replace_all(source, replacement().as_str()).into_owned()),
        "split" => O::Pieces(re.split(source).map(str::to_string).collect()),
        "as_str" => O::Pattern,
        _ => return None,
    })
}

/// A `Match` method over its span.
pub(super) enum MatchOut {
    Text(String),
    Int(i64),
}

pub(super) fn match_core(name: &str, source: &str, start: usize, end: usize) -> Option<MatchOut> {
    Some(match name {
        "as_str" => MatchOut::Text(source[start..end].to_string()),
        "start" => MatchOut::Int(start as i64),
        "end" => MatchOut::Int(end as i64),
        _ => return None,
    })
}

/// A `Captures` method: a group lookup resolved to its span, or the count.
pub(super) enum CapturesOut {
    Int(i64),
    /// The queried group's span, None when absent, out of range, or unmatched.
    OptSpan(Option<(usize, usize)>),
}

pub(super) fn captures_core<'n>(
    name: &str,
    groups: &[Option<(usize, usize)>],
    mut names: impl Iterator<Item = (&'n str, usize)>,
    args: &impl Args,
) -> Result<Option<CapturesOut>> {
    use CapturesOut as O;
    Ok(Some(match name {
        "get" => {
            let index = match args.int(0) {
                Some(i) if i >= 0 => i as usize,
                _ => bail!("captures get needs a non-negative index"),
            };
            O::OptSpan(groups.get(index).copied().flatten())
        }
        "name" => {
            let wanted = args.text(0);
            let index = names.find_map(|(n, i)| (n == wanted).then_some(i));
            O::OptSpan(index.and_then(|i| groups.get(i).copied().flatten()))
        }
        "len" => O::Int(groups.len() as i64),
        _ => return Ok(None),
    }))
}

// -- duration --------------------------------------------------------------

pub(super) enum DurOut {
    Int(i64),
    Float(f64),
    Bool(bool),
}

/// `Duration` accessors over the real `secs` plus `nanos` split, exactly the
/// std methods per name.
pub(super) fn duration_core(name: &str, secs: u64, nanos: u32) -> Option<DurOut> {
    use DurOut as O;
    let total = u128::from(secs) * 1_000_000_000 + u128::from(nanos);
    Some(match name {
        "as_secs" => O::Int(secs as i64),
        "as_millis" => O::Int((total / 1_000_000) as i64),
        "as_micros" => O::Int((total / 1_000) as i64),
        "as_nanos" => O::Int(total as i64),
        "subsec_nanos" => O::Int(i64::from(nanos)),
        "subsec_millis" => O::Int(i64::from(nanos / 1_000_000)),
        "subsec_micros" => O::Int(i64::from(nanos / 1_000)),
        "as_secs_f64" => O::Float(secs as f64 + f64::from(nanos) / 1e9),
        "is_zero" => O::Bool(total == 0),
        _ => return None,
    })
}

// -- datetime ---------------------------------------------------------------

pub(super) enum DateOut {
    Int(i64),
    Text(String),
}

/// `DateTime` accessors over the stored unix timestamp. `local` selects the
/// local timezone for `format`, everything else reads the UTC view, exactly
/// like the fast engine always did.
pub(super) fn datetime_core(
    name: &str,
    secs: i64,
    nanos: u32,
    local: bool,
    args: &impl Args,
) -> Option<DateOut> {
    use DateOut as O;
    use chrono::{DateTime, Datelike, Local, Timelike, Utc};
    let utc: DateTime<Utc> = DateTime::from_timestamp(secs, nanos).unwrap_or_default();
    Some(match name {
        "timestamp" => O::Int(secs),
        "timestamp_millis" => O::Int(secs * 1000 + i64::from(nanos / 1_000_000)),
        "to_rfc3339" => O::Text(utc.to_rfc3339()),
        "format" => {
            let fmt = args.text(0);
            if local {
                O::Text(utc.with_timezone(&Local).format(&fmt).to_string())
            } else {
                O::Text(utc.format(&fmt).to_string())
            }
        }
        "year" => O::Int(i64::from(utc.year())),
        "month" => O::Int(i64::from(utc.month())),
        "day" => O::Int(i64::from(utc.day())),
        "hour" => O::Int(i64::from(utc.hour())),
        "minute" => O::Int(i64::from(utc.minute())),
        "second" => O::Int(i64::from(utc.second())),
        _ => return None,
    })
}

// -- http and process scalars ----------------------------------------------

/// `StatusCode` accessors over the numeric code.
pub(super) enum StatusOut {
    Int(i64),
    Bool(bool),
}

pub(super) fn status_core(name: &str, code: i64) -> Option<StatusOut> {
    use StatusOut as O;
    Some(match name {
        "as_u16" | "as_int" => O::Int(code),
        "is_success" => O::Bool((200..300).contains(&code)),
        "is_client_error" => O::Bool((400..500).contains(&code)),
        "is_server_error" => O::Bool((500..600).contains(&code)),
        _ => return None,
    })
}

/// `HeaderValue` accessors over the header's text.
pub(super) enum HeaderOut {
    /// `to_str` answers `Ok(text)`, like the real fallible accessor.
    Ok(String),
    Text(String),
}

pub(super) fn header_value_core(name: &str, text: String) -> Option<HeaderOut> {
    Some(match name {
        "to_str" => HeaderOut::Ok(text),
        "as_str" | "as_string" | "to_string" => HeaderOut::Text(text),
        _ => return None,
    })
}

/// `ExitStatus` accessors over the flag and the optional code.
pub(super) enum ExitOut {
    Bool(bool),
    /// `code()`: `Some(code)` normally, `None` after death by signal.
    OptInt(Option<i64>),
}

pub(super) fn exit_status_core(name: &str, success: bool, code: Option<i64>) -> Option<ExitOut> {
    Some(match name {
        "success" => ExitOut::Bool(success),
        "code" => ExitOut::OptInt(code),
        _ => return None,
    })
}

/// The `colored` crate as string methods, shared so tokio scripts color their
/// output the same way. Returns the styled text as a plain string carrying
/// ANSI codes, so chaining and printing both work. Honors the crate's own
/// NO_COLOR and terminal detection.
pub(super) fn color_core(s: &str, name: &str) -> Option<String> {
    use colored::Colorize;
    let out = match name {
        "red" => s.red(),
        "green" => s.green(),
        "yellow" => s.yellow(),
        "blue" => s.blue(),
        "magenta" | "purple" => s.magenta(),
        "cyan" => s.cyan(),
        "white" => s.white(),
        "black" => s.black(),
        "bright_red" => s.bright_red(),
        "bright_green" => s.bright_green(),
        "bright_yellow" => s.bright_yellow(),
        "bright_blue" => s.bright_blue(),
        "bright_cyan" => s.bright_cyan(),
        "on_red" => s.on_red(),
        "on_green" => s.on_green(),
        "on_blue" => s.on_blue(),
        "bold" => s.bold(),
        "dimmed" => s.dimmed(),
        "italic" => s.italic(),
        "underline" => s.underline(),
        "reversed" => s.reversed(),
        "clear" | "normal" => s.normal(),
        _ => return None,
    };
    Some(out.to_string())
}