serpent-serializer 0.1.0

Serialize Lua values to round-trippable Lua source with cycle and shared-reference handling
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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! The serializer core.
//!
//! Translates a [`Value`] graph to Lua source. This follows serpent's `val2str`
//! recursion and top-level assembly: array-first key ordering, short vs bracket
//! key notation, shared and cyclic reference wiring through a self-reference
//! section, and the `do ... return name end` wrapper when a name is set.

use crate::numfmt;
use crate::options::Options;
use crate::quote::quote;
use crate::value::{Ident, Key, Table, Value};
use std::collections::HashMap;

/// The 22 Lua reserved words. String keys that are keywords never use short
/// notation.
const KEYWORDS: &[&str] = &[
    "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
    "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while",
];

fn is_keyword(s: &str) -> bool {
    KEYWORDS.contains(&s)
}

/// Serializer state carried through the recursion.
struct Serializer<'o> {
    opts: &'o Options,
    space: &'static str,
    huge: bool,
    maxl: usize,
    maxlen: Option<i64>,
    numformat: String,
    iname: String,
    comm: Option<usize>,
    /// Map from a reference identity to the path expression where it was placed.
    seen: HashMap<Ident, String>,
    /// Self-reference section statements. Index 0 is the helper-table decl.
    sref: Vec<String>,
    /// Symbol table for gensym: matched substring to stable counter.
    syms: HashMap<String, usize>,
    symn: usize,
    /// tostring of the first non-serializable value reached under `fatal`.
    /// serpent raises `error("Can't serialize "..tostring(s))` at that point.
    /// Recording the text lets the top level build the same message.
    fatal_value: Option<String>,
}

/// The recursion context passed to [`Serializer::val2str`].
///
/// Grouping these together keeps the call sites readable. Transposing two
/// borrowed strings in a positional list would compile and emit wrong output,
/// so the names carry the meaning here instead of the argument order.
#[derive(Clone, Copy)]
struct Frame<'a> {
    /// The key this value sits under, if any.
    name: Option<&'a Key>,
    /// The indentation unit, when output is multi-line.
    indent: Option<&'a str>,
    /// The path to register in `seen` for this value, overriding the computed
    /// path. serpent's `insref`.
    insref: Option<&'a str>,
    /// The access path prefix this value hangs off, such as `_.a`.
    path: Option<&'a str>,
    /// Whether this element uses array notation with no `key =` prefix.
    plainindex: bool,
    /// The nesting depth, starting at 0.
    level: usize,
}

impl<'o> Serializer<'o> {
    fn new(opts: &'o Options) -> Self {
        let name = opts.name.clone().unwrap_or_default();
        let iname = format!("_{name}");
        let space = if opts.compact { "" } else { " " };
        Serializer {
            space,
            huge: !opts.nohuge,
            maxl: opts.maxlevel.unwrap_or(usize::MAX),
            maxlen: opts.maxlength,
            numformat: opts
                .numformat
                .clone()
                .unwrap_or_else(|| "%.17g".to_string()),
            sref: vec![format!("local {iname}={{}}")],
            iname,
            comm: opts.comment,
            seen: HashMap::new(),
            syms: HashMap::new(),
            symn: 0,
            fatal_value: None,
            opts,
        }
    }

    /// serpent's `gensym`: build a stable identifier for a reference used as a
    /// key. Strip non-alphanumerics from the identity text, then remap each
    /// `[0-9][A-Za-z0-9]+` run to a stable counter, and prefix `_`.
    fn gensym(&mut self, raw: &str) -> String {
        let stripped: String = raw.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
        let remapped = self.remap_runs(&stripped);
        format!("_{remapped}")
    }

    /// Replace each maximal `[0-9][A-Za-z0-9]+` run with a stable 1-based
    /// counter assigned in first-seen order.
    fn remap_runs(&mut self, s: &str) -> String {
        let b = s.as_bytes();
        let mut out = String::new();
        let mut i = 0;
        while i < b.len() {
            if b[i].is_ascii_digit() {
                // A run must be a digit followed by one or more word chars.
                let start = i;
                i += 1;
                let mut count = 0;
                while i < b.len() && b[i].is_ascii_alphanumeric() {
                    i += 1;
                    count += 1;
                }
                let run = &s[start..i];
                if count >= 1 {
                    let n = *self.syms.entry(run.to_string()).or_insert_with(|| {
                        self.symn += 1;
                        self.symn
                    });
                    out.push_str(&n.to_string());
                } else {
                    out.push_str(run);
                }
            } else {
                out.push(b[i] as char);
                i += 1;
            }
        }
        out
    }

    /// serpent's `safestr`: a scalar value as a Lua literal.
    fn safestr(&self, v: &Value) -> String {
        match v {
            Value::Number(n) => {
                if self.huge {
                    if n.is_infinite() {
                        return if *n > 0.0 {
                            "1/0 --[[math.huge]]".to_string()
                        } else {
                            "-1/0 --[[-math.huge]]".to_string()
                        };
                    }
                    if n.is_nan() {
                        return "0/0".to_string();
                    }
                }
                numfmt::format(&self.numformat, *n)
            }
            Value::Str(s) => quote(s),
            Value::Bool(b) => b.to_string(),
            Value::Nil => "nil".to_string(),
            // Non-scalar reaching safestr means a fallback tostring; use a
            // placeholder path text.
            other => quote(tostring(other).as_bytes()),
        }
    }

    /// serpent's `comment`: an inline `--[[...]]` comment, when enabled and the
    /// level is under the threshold.
    fn comment(&self, text: &str, level: usize) -> String {
        match self.comm {
            Some(threshold) if level < threshold => format!(" --[[{text}]]"),
            _ => String::new(),
        }
    }

    /// serpent's `safename`: build an access path and return `(path, safe)`.
    fn safename(&self, path: Option<&str>, name: Option<&Key>) -> (String, String) {
        let plain_name = match name {
            Some(Key::Str(s)) => std::str::from_utf8(s)
                .ok()
                .filter(|n| is_plain_ident(n) && !is_keyword(n))
                .map(str::to_string),
            _ => None,
        };
        let (safe, is_plain) = match &plain_name {
            Some(n) => (n.clone(), true),
            None => {
                let key_val = name.map_or(Value::Str(Vec::new()), Key::to_value);
                (format!("[{}]", self.safestr(&key_val)), false)
            }
        };
        let joiner = if is_plain && path.is_some() { "." } else { "" };
        let full = format!("{}{}{}", path.unwrap_or(""), joiner, safe);
        (full, safe)
    }

    /// serpent's `val2str`. Returns the element text and appends any needed
    /// self-reference statements.
    fn val2str(&mut self, t: &Value, frame: Frame) -> String {
        let level = frame.level;
        let (spath, sname) = self.safename(frame.path, frame.name);
        let tag = self.build_tag(frame.name, &sname, frame.plainindex);

        // Already seen: emit nil and wire the reference in the self-ref section.
        if let Some(id) = t.ident() {
            if let Some(prev) = self.seen.get(&id).cloned() {
                self.sref
                    .push(format!("{spath}{}={}{prev}", self.space, self.space));
                return format!("{tag}nil{}", self.comment("ref", level));
            }
        }

        // Metamethods. When a table has __serialize or __tostring and
        // metatostring is not false, the successful result replaces the table.
        // __serialize wins over __tostring. A raising metamethod is ignored.
        let replaced = self.apply_metamethods(t, frame.insref.unwrap_or(&spath));
        let t = replaced.as_ref().unwrap_or(t);

        match t {
            Value::Table(tab) => self.table_to_str(tab, &tag, &spath, frame),
            Value::Global(_) => {
                if let Some(id) = t.ident() {
                    self.seen
                        .insert(id, frame.insref.unwrap_or(&spath).to_string());
                }
                format!("{tag}{}", self.globerr(t, level))
            }
            Value::Function(f) => {
                if let Some(id) = t.ident() {
                    self.seen
                        .insert(id, frame.insref.unwrap_or(&spath).to_string());
                }
                if self.opts.nocode {
                    return format!(
                        "{tag}function() --[[..skipped..]] end{}",
                        self.comment("", level)
                    );
                }
                match &f.bytecode {
                    Some(code) => {
                        let quoted = quote(code);
                        format!(
                            "{tag}((loadstring or load)({quoted},'@serialized')){}",
                            self.comment("", level)
                        )
                    }
                    None => format!("{tag}{}", self.globerr(t, level)),
                }
            }
            _ => format!("{tag}{}", self.safestr(t)),
        }
    }

    /// Build the `key =` prefix for an element.
    fn build_tag(&self, name: Option<&Key>, sname: &str, plainindex: bool) -> String {
        if plainindex {
            match name {
                Some(Key::Number(_)) => String::new(),
                Some(k) => {
                    let raw = tostring(&k.to_value());
                    format!("{raw}{}={}", self.space, self.space)
                }
                None => String::new(),
            }
        } else if name.is_some() {
            format!("{sname}{}={}", self.space, self.space)
        } else {
            String::new()
        }
    }

    /// Try the table's metamethods. Returns the replacement value when one
    /// succeeds. `__serialize` is preferred over `__tostring`. A metamethod that
    /// errors is skipped. The table is marked seen at `seen_path` when a
    /// metamethod applies, matching serpent's `seen[t] = insref or spath`.
    fn apply_metamethods(&mut self, t: &Value, seen_path: &str) -> Option<Value> {
        let Value::Table(tab) = t else {
            return None;
        };
        if self.opts.metatostring == Some(false) {
            return None;
        }
        let ser = tab.serialize_meta();
        let tos = tab.tostring_meta();
        if ser.is_none() && tos.is_none() {
            return None;
        }
        // __serialize wins when it succeeds, else __tostring.
        let result = ser
            .and_then(|f| f().ok())
            .or_else(|| tos.and_then(|f| f().ok()))?;
        if let Some(id) = t.ident() {
            self.seen.insert(id, seen_path.to_string());
        }
        Some(result)
    }

    /// serpent's `globerr`: a global name, a fallback string, or an error.
    ///
    /// A `Global` with a non-empty name is a known global and emits its name.
    /// An empty name means the value has no global mapping, matching an unknown
    /// userdata: it falls back to a quoted string, or records a fatal value when
    /// `fatal` is set so the top level can raise an error.
    fn globerr(&mut self, v: &Value, level: usize) -> String {
        if let Value::Global(g) = v {
            if !g.name.is_empty() {
                return format!("{}{}", g.name, self.comment(&g.name, level));
            }
        }
        // A value with no global mapping stands in for unknown userdata, whose
        // Lua tostring is `userdata: 0x...`. Build that address form for both
        // the fallback string and the fatal message.
        let text = match v {
            Value::Global(g) if g.name.is_empty() => format!("userdata: 0x{:012x}", g.id),
            _ => tostring(v),
        };
        if !self.opts.fatal {
            return self.safestr(&Value::Str(text.into_bytes()));
        }
        // fatal: record the value text for the error message. Keep the first one.
        if self.fatal_value.is_none() {
            self.fatal_value = Some(text.clone());
        }
        // The output is discarded once a fatal value is recorded, so the return
        // value here does not reach the caller.
        self.safestr(&Value::Str(text.into_bytes()))
    }

    fn table_to_str(&mut self, tab: &Table, tag: &str, spath: &str, frame: Frame) -> String {
        let Frame {
            indent,
            insref,
            level,
            ..
        } = frame;
        if level >= self.maxl {
            return format!("{tag}{{}}{}", self.comment("maxlvl", level));
        }
        let id = Ident::Table(tab.id());
        self.seen.insert(id, insref.unwrap_or(spath).to_string());
        if tab.is_empty() {
            let text = tab_tostring(tab);
            return format!("{tag}{{}}{}", self.comment(&text, level));
        }
        if let Some(ml) = self.maxlen {
            if ml < 0 {
                return format!("{tag}{{}}{}", self.comment("maxlen", level));
            }
        }

        let entries = tab.entries();
        let border = tab.border();
        let maxn = match self.opts.maxnum {
            Some(m) => border.min(m),
            None => border,
        };

        // Index the entries by key once for O(1) value lookup. Keys are unique
        // under `Key::same`, so each projection maps to a single slot.
        let index: HashMap<KeyId, usize> = entries
            .iter()
            .enumerate()
            .filter_map(|(i, (k, _))| key_id(k).map(|id| (id, i)))
            .collect();
        let lookup = |key: &Key| -> Option<Value> {
            key_id(key)
                .and_then(|id| index.get(&id))
                .map(|&i| entries[i].1.clone())
        };

        // Ordered key list: array indices 1..maxn first, then remaining keys.
        let mut o: Vec<Key> = (1..=maxn).map(|i| Key::Number(i as f64)).collect();
        if self.opts.maxnum.is_none() || o.len() < self.opts.maxnum.unwrap() {
            for (k, _) in &entries {
                if !is_array_index(k, maxn) {
                    o.push(k.clone());
                }
            }
        }
        if let Some(m) = self.opts.maxnum {
            if o.len() > m {
                o.truncate(m);
            }
        }
        if (self.opts.sortkeys || self.opts.sortfn.is_some()) && o.len() > maxn {
            self.sort_keys(&mut o, &entries);
        }
        let sparse = self.opts.sparse && o.len() > maxn;

        // Compute the table's seen-path once, not per element.
        let seen_t = self.seen.get(&Ident::Table(tab.id())).cloned();

        let mut out: Vec<String> = Vec::new();
        for (n, key) in o.iter().enumerate() {
            let idx = n + 1;
            let value = lookup(key);
            let plainindex = idx <= maxn && !sparse;

            if self.should_skip(key, value.as_ref(), sparse) {
                continue;
            }

            let is_complex = matches!(key, Key::Table(_) | Key::Function(_) | Key::Global(_));
            if is_complex {
                self.emit_complex_key(tab, key, value, indent);
            } else {
                let v = value.unwrap_or(Value::Nil);
                let text = self.val2str(
                    &v,
                    Frame {
                        name: Some(key),
                        indent,
                        insref: None,
                        path: seen_t.as_deref(),
                        plainindex,
                        level: level + 1,
                    },
                );
                let len = text.len() as i64;
                out.push(text);
                if let Some(ml) = self.maxlen.as_mut() {
                    *ml -= len;
                    if *ml < 0 {
                        break;
                    }
                }
            }
        }

        self.assemble_table(tab, tag, indent, &out, level)
    }

    /// A complex key (table/function/global). Emit its assignment into the
    /// self-reference section, declaring a helper local first if needed.
    fn emit_complex_key(
        &mut self,
        tab: &Table,
        key: &Key,
        value: Option<Value>,
        indent: Option<&str>,
    ) {
        let key_val = key.to_value();
        let key_id = key_val.ident();
        let key_seen = key_id.as_ref().and_then(|i| self.seen.get(i)).cloned();
        let key_global = match key {
            Key::Global(g) => Some(g.name.clone()),
            _ => None,
        };

        if key_seen.is_none() && key_global.is_none() {
            self.sref.push("placeholder".to_string());
            let idx = self.sref.len() - 1;
            let sym = self.gensym(&tostring(&key_val));
            let iname = self.iname.clone();
            let (sname, _) = self.safename(Some(&iname), Some(&Key::Str(sym.into_bytes())));
            let stmt = self.val2str(
                &key_val,
                Frame {
                    name: Some(&Key::Str(sname.clone().into_bytes())),
                    indent,
                    insref: Some(&sname),
                    path: Some(&iname),
                    plainindex: true,
                    level: 0,
                },
            );
            self.sref[idx] = stmt;
        }

        self.sref.push("placeholder".to_string());
        let idx = self.sref.len() - 1;
        let seen_t = self
            .seen
            .get(&Ident::Table(tab.id()))
            .cloned()
            .unwrap_or_default();
        // Recompute seen[key] here: the helper serialization above may have just
        // registered the key at its helper-table path, matching serpent's
        // `seen[key] or globals[key] or gensym(key)` at LHS-building time.
        let key_seen_now = key_id.as_ref().and_then(|i| self.seen.get(i)).cloned();
        let key_ref = key_seen_now
            .or(key_global)
            .unwrap_or_else(|| self.gensym(&tostring(&key_val)));
        let path = format!("{seen_t}[{key_ref}]");
        let value = value.unwrap_or(Value::Nil);
        let val_seen = value.ident().and_then(|i| self.seen.get(&i)).cloned();
        let rhs = match val_seen {
            Some(p) => p,
            // serpent calls val2str(value, nil, indent, path) so `insref` is the
            // path and the fifth path argument is nil. That makes the value
            // register at `path`, not at `path[""]`.
            None => self.val2str(
                &value,
                Frame {
                    name: None,
                    indent,
                    insref: Some(&path),
                    path: None,
                    plainindex: false,
                    level: 0,
                },
            ),
        };
        self.sref[idx] = format!("{path}{}={}{rhs}", self.space, self.space);
    }

    /// Assemble the final table text from the emitted element list.
    fn assemble_table(
        &self,
        tab: &Table,
        tag: &str,
        indent: Option<&str>,
        out: &[String],
        level: usize,
    ) -> String {
        let prefix = indent.map_or(String::new(), |ind| ind.repeat(level));
        let head = match indent {
            Some(ind) => format!("{{\n{prefix}{ind}"),
            None => "{".to_string(),
        };
        let sep = match indent {
            Some(ind) => format!(",\n{prefix}{ind}"),
            None => format!(",{}", self.space),
        };
        let body = out.join(&sep);
        let tail = match indent {
            Some(_) => format!("\n{prefix}}}"),
            None => "}".to_string(),
        };
        let table_text = match &self.opts.custom {
            Some(f) => f(tag, &head, &body, &tail, level),
            None => format!("{tag}{head}{body}{tail}"),
        };
        let text = tab_tostring(tab);
        format!("{table_text}{}", self.comment(&text, level))
    }

    /// Whether an element is skipped by the ignore filters or sparse-nil rule.
    fn should_skip(&self, key: &Key, value: Option<&Value>, sparse: bool) -> bool {
        if let Some(v) = value {
            if let Some(ig) = &self.opts.valignore {
                if let Some(id) = v.ident() {
                    if ig.contains(&id) {
                        return true;
                    }
                }
            }
            if let Some(ig) = &self.opts.valignore_scalar {
                if ig.iter().any(|x| x == v) {
                    return true;
                }
            }
        }
        if let Some(allow) = &self.opts.keyallow {
            if !allow.iter().any(|k| k == key) {
                return true;
            }
        }
        if let Some(ignore) = &self.opts.keyignore {
            if ignore.iter().any(|k| k == key) {
                return true;
            }
        }
        if let Some(tignore) = &self.opts.valtypeignore {
            let tn = value.map_or("nil", type_name);
            if tignore.contains(tn) {
                return true;
            }
        }
        if sparse && value.is_none() {
            return true;
        }
        false
    }

    /// serpent's `alphanumsort`, or the custom sort when set.
    fn sort_keys(&self, o: &mut Vec<Key>, entries: &[(Key, Value)]) {
        if let Some(f) = &self.opts.sortfn {
            // The closure reorders the keys directly and can read values from
            // `entries`, so no value round-trip and no key remap is needed.
            f(o, entries);
            return;
        }
        // Default: sort by a computed string. A numeric key whose value is a
        // positive integer landing on a filled slot of the ordered list ranks
        // first. serpent tests `o[key] ~= nil`, which holds for any integer key
        // in 1..#o, not only the array indices 1..maxn.
        let len = o.len();
        o.sort_by_key(|a| sortkey(a, len));
    }
}

/// Format a table like Lua's default `tostring`: `table: 0x...`.
fn tab_tostring(tab: &Table) -> String {
    format!("table: 0x{:012x}", tab.id())
}

/// Lua-style default `tostring` for non-string values used in comments and
/// fallbacks.
fn tostring(v: &Value) -> String {
    match v {
        Value::Nil => "nil".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => {
            if n.is_nan() {
                "nan".to_string()
            } else if n.is_infinite() {
                if *n > 0.0 {
                    "inf".to_string()
                } else {
                    "-inf".to_string()
                }
            } else {
                numfmt::format("%.14g", *n)
            }
        }
        Value::Str(s) => String::from_utf8_lossy(s).into_owned(),
        Value::Table(t) => tab_tostring(t),
        Value::Function(f) => format!("function: 0x{:012x}", f.id),
        Value::Global(g) => g.name.clone(),
    }
}

/// The Lua type name of a value.
fn type_name(v: &Value) -> &'static str {
    match v {
        Value::Nil => "nil",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::Str(_) => "string",
        Value::Table(_) => "table",
        Value::Function(_) => "function",
        Value::Global(_) => "userdata",
    }
}

/// A valid Lua identifier: starts with a letter or underscore, then word chars.
fn is_plain_ident(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Whether a key is one of the array indices 1..maxn.
fn is_array_index(k: &Key, maxn: usize) -> bool {
    match k {
        Key::Number(x) => {
            let f = *x;
            f.fract() == 0.0 && f >= 1.0 && f <= maxn as f64
        }
        _ => false,
    }
}

/// A hashable projection of a key, used to index a table's entries for O(1)
/// value lookup.
///
/// Numbers use their bit pattern after normalizing `-0.0` to `0.0`, which keeps
/// the projection consistent with [`Key::same`] (where `-0.0 == 0.0`). A `NaN`
/// key returns `None`, since Lua forbids `NaN` keys and [`Key::same`] never
/// matches two `NaN` values.
#[derive(PartialEq, Eq, Hash)]
enum KeyId {
    Bool(bool),
    Number(u64),
    Str(Vec<u8>),
    Table(usize),
    Function(usize),
    Global(usize),
}

fn key_id(k: &Key) -> Option<KeyId> {
    Some(match k {
        Key::Bool(b) => KeyId::Bool(*b),
        Key::Number(n) if n.is_nan() => return None,
        Key::Number(n) => KeyId::Number(if *n == 0.0 { 0.0_f64 } else { *n }.to_bits()),
        Key::Str(s) => KeyId::Str(s.clone()),
        Key::Table(t) => KeyId::Table(t.id()),
        Key::Function(f) => KeyId::Function(f.id),
        Key::Global(g) => KeyId::Global(g.id),
    })
}

/// Build serpent's sort string for a key.
///
/// `list_len` is the length of the ordered key list. A numeric key whose value
/// is a positive integer at or below `list_len` gets the `"0"` prefix, matching
/// serpent's `o[key] ~= nil` test over the ordered list. Every other key falls
/// back to the type rank.
fn sortkey(k: &Key, list_len: usize) -> String {
    let on_filled_slot = match k {
        Key::Number(x) => x.fract() == 0.0 && *x >= 1.0 && *x <= list_len as f64,
        _ => false,
    };
    let prefix = if on_filled_slot {
        "0"
    } else {
        match k {
            Key::Number(_) => "a",
            Key::Str(_) => "b",
            _ => "z",
        }
    };
    let body = pad_numbers(&key_tostring(k));
    format!("{prefix}{body}")
}

/// serpent's `padnum`: zero-pad each digit run to 12 places.
fn pad_numbers(s: &str) -> String {
    let mut out = String::new();
    let b = s.as_bytes();
    let mut i = 0;
    while i < b.len() {
        if b[i].is_ascii_digit() {
            let start = i;
            while i < b.len() && b[i].is_ascii_digit() {
                i += 1;
            }
            let num = &s[start..i];
            let val: u64 = num.parse().unwrap_or(0);
            out.push_str(&format!("{val:012}"));
        } else {
            out.push(b[i] as char);
            i += 1;
        }
    }
    out
}

/// `tostring` of a key for sort-string building.
fn key_tostring(k: &Key) -> String {
    tostring(&k.to_value())
}

/// Serialize a value graph with the given options.
///
/// This is the raw entry point. Returns the Lua source, or an error when
/// `fatal` is set and a non-serializable value is reached.
///
/// # Errors
///
/// Returns [`SerError`] when `opts.fatal` is set and a value cannot be
/// serialized as data.
pub fn serialize(t: &Value, opts: &Options) -> Result<String, SerError> {
    let mut s = Serializer::new(opts);
    let name = opts.name.clone();
    let indent = opts.indent.clone();
    let sepr = match &indent {
        Some(_) => "\n".to_string(),
        None => format!(";{}", s.space),
    };
    let top_name = name.as_ref().map(|n| Key::Str(n.clone().into_bytes()));
    let body = s.val2str(
        t,
        Frame {
            name: top_name.as_ref(),
            indent: indent.as_deref(),
            insref: None,
            path: None,
            plainindex: false,
            level: 0,
        },
    );

    if let Some(value) = s.fatal_value.take() {
        return Err(SerError::NotSerializable(value));
    }

    let tail = if s.sref.len() > 1 {
        format!("{}{sepr}", s.sref.join(&sepr))
    } else {
        String::new()
    };
    let warn = if opts.comment.is_some() && s.sref.len() > 1 {
        format!(
            "{}--[[incomplete output with shared/self-references skipped]]",
            s.space
        )
    } else {
        String::new()
    };

    let result = match name {
        None => format!("{body}{warn}"),
        Some(n) => format!("do local {body}{sepr}{tail}return {n}{sepr}end"),
    };
    Ok(result)
}

/// A serialization error.
#[derive(Debug, PartialEq, Eq)]
pub enum SerError {
    /// A value could not be serialized and `fatal` was set. Carries the value's
    /// `tostring` text, so the message names the value that failed.
    NotSerializable(String),
}

impl std::fmt::Display for SerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SerError::NotSerializable(value) => write!(f, "Can't serialize {value}"),
        }
    }
}

impl std::error::Error for SerError {}