neovm-core 0.0.2

Core runtime structures for NeoVM
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Case conversion and character builtins.
//!
//! Implements `capitalize`, `upcase-initials`, and `char-resolve-modifiers`.

use super::error::{EvalResult, Flow, signal};
use super::symbol::Obarray;
use super::syntax::forward_word;
use super::value::*;
use crate::buffer::Buffer;
use crate::emacs_core::value::ValueKind;
use crate::heap_types::LispString;

// ---------------------------------------------------------------------------
// Argument helpers
// ---------------------------------------------------------------------------

fn expect_args(name: &str, args: &[Value], n: usize) -> Result<(), Flow> {
    if args.len() != n {
        Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
        ))
    } else {
        Ok(())
    }
}

fn expect_min_max_args(name: &str, args: &[Value], min: usize, max: usize) -> Result<(), Flow> {
    if args.len() < min || args.len() > max {
        Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
        ))
    } else {
        Ok(())
    }
}

fn expect_int(value: &Value) -> Result<i64, Flow> {
    match value.kind() {
        ValueKind::Fixnum(n) => Ok(n),
        other => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("integerp"), *value],
        )),
    }
}

// ---------------------------------------------------------------------------
// Character helpers
// ---------------------------------------------------------------------------

const CHAR_META: i64 = 0x8000000;
const CHAR_CTL: i64 = 0x4000000;
const CHAR_SHIFT: i64 = 0x2000000;
const CHAR_HYPER: i64 = 0x1000000;
const CHAR_SUPER: i64 = 0x0800000;
const CHAR_ALT: i64 = 0x0400000;
const CHAR_MODIFIER_MASK: i64 =
    CHAR_META | CHAR_CTL | CHAR_SHIFT | CHAR_HYPER | CHAR_SUPER | CHAR_ALT;

/// Convert a character code to a Rust char (if it's a valid Unicode scalar value).
fn code_to_char(code: i64) -> Option<char> {
    if (0..=0x10FFFF).contains(&code) {
        char::from_u32(code as u32)
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Case conversion helpers
// ---------------------------------------------------------------------------

/// Uppercase a single character code, returning the new code.
fn upcase_char(code: i64) -> i64 {
    if preserve_casefiddle_upcase_payload(code) {
        return code;
    }
    match code {
        223 => return 7838,
        452 | 497 => return code + 1,
        454 | 457 | 460 | 499 => return code - 1,
        455 | 458 => return code + 1,
        8064..=8071 | 8080..=8087 | 8096..=8103 => return code + 8,
        8115 | 8131 | 8179 => return code + 9,
        _ => {}
    }
    match code_to_char(code) {
        Some(c) => {
            let mut upper = c.to_uppercase();
            // to_uppercase() may yield multiple chars (e.g. German eszett);
            // take only the first to stay consistent with Emacs behavior.
            upper.next().map(|u| u as i64).unwrap_or(code)
        }
        None => code,
    }
}

fn preserve_casefiddle_upcase_payload(code: i64) -> bool {
    matches!(
        code,
        329
            | 411
            | 453
            | 456
            | 459
            | 496
            | 498
            | 612
            | 912
            | 944
            | 1415
            | 4304..=4346
            | 4349..=4351
            | 7306
            | 7830..=7834
            | 8016
            | 8018
            | 8020
            | 8022
            | 8072..=8079
            | 8088..=8095
            | 8104..=8111
            | 8114
            | 8116
            | 8118..=8119
            | 8124
            | 8130
            | 8132
            | 8134..=8135
            | 8140
            | 8146..=8147
            | 8150..=8151
            | 8162..=8164
            | 8166..=8167
            | 8178
            | 8180
            | 8182..=8183
            | 8188
            | 42957
            | 42959
            | 42963
            | 42965
            | 42971
            | 64256..=64262
            | 64275..=64279
            | 68976..=68997
            | 93883..=93907
    )
}

fn titlecase_from_uppercase_expansion(expansion: &[char]) -> String {
    let mut result = String::new();
    let mut seen_cased = false;

    for uc in expansion {
        let is_cased = uc.is_uppercase() || uc.is_lowercase();
        if !seen_cased {
            result.push(*uc);
            if is_cased {
                seen_cased = true;
            }
            continue;
        }

        if is_cased {
            for lc in uc.to_lowercase() {
                result.push(lc);
            }
        } else {
            result.push(*uc);
        }
    }

    result
}

fn titlecase_combining_iota_override(code: i64) -> Option<&'static str> {
    match code {
        8114 => Some("\u{1FBA}\u{0345}"),
        8116 => Some("\u{0386}\u{0345}"),
        8119 => Some("\u{0391}\u{0342}\u{0345}"),
        8130 => Some("\u{1FCA}\u{0345}"),
        8132 => Some("\u{0389}\u{0345}"),
        8135 => Some("\u{0397}\u{0342}\u{0345}"),
        8178 => Some("\u{1FFA}\u{0345}"),
        8180 => Some("\u{038F}\u{0345}"),
        8183 => Some("\u{03A9}\u{0342}\u{0345}"),
        _ => None,
    }
}

fn titlecase_uses_precomposed_upcase(code: i64) -> bool {
    matches!(
        code,
        8064..=8071
            | 8072..=8111
            | 8115
            | 8124
            | 8131
            | 8140
            | 8179
            | 8188
    )
}

fn titlecase_word_initial(c: char) -> String {
    let code = c as i64;
    if let Some(explicit) = titlecase_combining_iota_override(code) {
        return explicit.to_string();
    }

    let expansion: Vec<char> = c.to_uppercase().collect();
    if expansion.len() > 1 && !titlecase_uses_precomposed_upcase(code) {
        return titlecase_from_uppercase_expansion(&expansion);
    }

    if let Some(mapped) = code_to_char(upcase_char(code)) {
        mapped.to_string()
    } else {
        c.to_uppercase().collect()
    }
}

fn push_multibyte_char_code(out: &mut Vec<u8>, code: u32) {
    let mut buf = [0u8; crate::emacs_core::emacs_char::MAX_MULTIBYTE_LENGTH];
    let len = crate::emacs_core::emacs_char::char_string(code, &mut buf);
    out.extend_from_slice(&buf[..len]);
}

fn push_multibyte_chars(out: &mut Vec<u8>, chars: impl IntoIterator<Item = char>) {
    for ch in chars {
        push_multibyte_char_code(out, ch as u32);
    }
}

fn ascii_word_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte >= 0x80
}

fn downcase_lisp_string_emacs_compat(text: &LispString) -> LispString {
    if !text.is_multibyte() {
        let bytes = text
            .as_bytes()
            .iter()
            .map(|byte| byte.to_ascii_lowercase())
            .collect();
        return LispString::from_unibyte(bytes);
    }

    let mut out = Vec::with_capacity(text.sbytes());
    for code in super::builtins::lisp_string_char_codes(text) {
        let code_i64 = code as i64;
        if code == 0x212A || preserve_downcase_case_string_payload(code_i64) {
            push_multibyte_char_code(&mut out, code);
            continue;
        }
        if let Some(ch) = code_to_char(code_i64) {
            push_multibyte_chars(&mut out, ch.to_lowercase());
        } else {
            push_multibyte_char_code(&mut out, code);
        }
    }
    LispString::from_emacs_bytes(out)
}

fn upcase_lisp_string_emacs_compat(text: &LispString) -> LispString {
    if !text.is_multibyte() {
        let bytes = text
            .as_bytes()
            .iter()
            .map(|byte| byte.to_ascii_uppercase())
            .collect();
        return LispString::from_unibyte(bytes);
    }

    let mut out = Vec::with_capacity(text.sbytes());
    for code in super::builtins::lisp_string_char_codes(text) {
        let code_i64 = code as i64;
        if code == 0x0131 || preserve_upcase_case_string_payload(code_i64) {
            push_multibyte_char_code(&mut out, code);
            continue;
        }
        if let Some(ch) = code_to_char(code_i64) {
            push_multibyte_chars(&mut out, ch.to_uppercase());
        } else {
            push_multibyte_char_code(&mut out, code);
        }
    }
    LispString::from_emacs_bytes(out)
}

fn capitalize_lisp_string(text: &LispString) -> LispString {
    if !text.is_multibyte() {
        let mut out = Vec::with_capacity(text.sbytes());
        let mut new_word = true;
        for &byte in text.as_bytes() {
            if ascii_word_byte(byte) {
                out.push(if new_word {
                    byte.to_ascii_uppercase()
                } else {
                    byte.to_ascii_lowercase()
                });
                new_word = false;
            } else {
                out.push(byte);
                new_word = true;
            }
        }
        return LispString::from_unibyte(out);
    }

    let mut out = Vec::with_capacity(text.sbytes());
    let mut new_word = true;
    for code in super::builtins::lisp_string_char_codes(text) {
        if let Some(ch) = code_to_char(code as i64) {
            if ch.is_alphanumeric() {
                if new_word {
                    push_multibyte_chars(&mut out, titlecase_word_initial(ch).chars());
                    new_word = false;
                } else {
                    push_multibyte_chars(&mut out, ch.to_lowercase());
                }
            } else {
                push_multibyte_char_code(&mut out, code);
                new_word = true;
            }
        } else {
            push_multibyte_char_code(&mut out, code);
            new_word = true;
        }
    }
    LispString::from_emacs_bytes(out)
}

fn upcase_initials_lisp_string(text: &LispString) -> LispString {
    if !text.is_multibyte() {
        let mut out = Vec::with_capacity(text.sbytes());
        let mut new_word = true;
        for &byte in text.as_bytes() {
            if ascii_word_byte(byte) {
                out.push(if new_word {
                    byte.to_ascii_uppercase()
                } else {
                    byte
                });
                new_word = false;
            } else {
                out.push(byte);
                new_word = true;
            }
        }
        return LispString::from_unibyte(out);
    }

    let mut out = Vec::with_capacity(text.sbytes());
    let mut new_word = true;
    for code in super::builtins::lisp_string_char_codes(text) {
        if let Some(ch) = code_to_char(code as i64) {
            if ch.is_alphanumeric() {
                if new_word {
                    push_multibyte_chars(&mut out, titlecase_word_initial(ch).chars());
                    new_word = false;
                } else {
                    push_multibyte_char_code(&mut out, code);
                }
            } else {
                push_multibyte_char_code(&mut out, code);
                new_word = true;
            }
        } else {
            push_multibyte_char_code(&mut out, code);
            new_word = true;
        }
    }
    LispString::from_emacs_bytes(out)
}

fn downcase_case_string_emacs_compat(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        let code = ch as i64;
        if ch == '\u{212A}' || preserve_downcase_case_string_payload(code) {
            out.push(ch);
            continue;
        }
        for low in ch.to_lowercase() {
            out.push(low);
        }
    }
    out
}

fn upcase_case_string_emacs_compat(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        let code = ch as i64;
        if ch == '\u{0131}' || preserve_upcase_case_string_payload(code) {
            out.push(ch);
            continue;
        }
        for up in ch.to_uppercase() {
            out.push(up);
        }
    }
    out
}

fn preserve_downcase_case_string_payload(code: i64) -> bool {
    matches!(
        code,
        7305
            | 42955
            | 42956
            | 42958
            | 42962
            | 42964
            | 42970
            | 42972
            | 68944..=68965
            | 93856..=93880
    )
}

fn preserve_upcase_case_string_payload(code: i64) -> bool {
    matches!(
        code,
        411
            | 612
            | 7306
            | 42957
            | 42959
            | 42963
            | 42965
            | 42971
            | 68976..=68997
            | 93883..=93907
    )
}

fn resolve_region(buf: &Buffer, beg: i64, end: i64) -> (usize, usize) {
    let point_min = buf.point_min_char() as i64 + 1;
    let point_max = buf.point_max_char() as i64 + 1;

    let mut a = beg.clamp(point_min, point_max);
    let mut b = end.clamp(point_min, point_max);
    if a > b {
        std::mem::swap(&mut a, &mut b);
    }

    let a_byte = buf.lisp_pos_to_accessible_byte(a);
    let b_byte = buf.lisp_pos_to_accessible_byte(b);
    (a_byte, b_byte)
}

fn resolve_case_region_in_buffers(
    buffers: &crate::buffer::BufferManager,
    beg: i64,
    end: i64,
    arg: Option<&Value>,
) -> Result<(usize, usize), Flow> {
    let buf = buffers
        .current_buffer()
        .ok_or_else(|| signal("error", vec![Value::string("No current buffer")]))?;

    if arg.is_some_and(|value| !value.is_nil()) {
        let mark = buf.mark().ok_or_else(|| {
            signal(
                "error",
                vec![Value::string(
                    "The mark is not set now, so there is no region",
                )],
            )
        })?;
        let pt = buf.point();
        return Ok((pt.min(mark), pt.max(mark)));
    }

    Ok(resolve_region(buf, beg, end))
}

fn replace_current_buffer_region_in_buffers(
    buffers: &mut crate::buffer::BufferManager,
    beg: usize,
    end: usize,
    replacement: &LispString,
    restore_point: bool,
) -> EvalResult {
    let buf = buffers
        .current_buffer_mut()
        .ok_or_else(|| signal("error", vec![Value::string("No current buffer")]))?;
    let saved_pt = buf.point();
    buf.delete_region(beg, end);
    buf.goto_char(beg);
    buf.insert_lisp_string(replacement);
    if restore_point {
        buf.goto_char(saved_pt.min(buf.point_max()));
    }
    Ok(Value::NIL)
}

fn casify_region_in_state(
    obarray: &Obarray,
    dynamic: &[OrderedRuntimeBindingMap],
    buffers: &mut crate::buffer::BufferManager,
    args: Vec<Value>,
    name: &str,
    transform: impl FnOnce(&LispString) -> LispString,
) -> EvalResult {
    expect_min_max_args(name, &args, 2, 3)?;
    let beg_val = expect_int(&args[0])?;
    let end_val = expect_int(&args[1])?;

    let (beg, end, text) = {
        let buf = buffers
            .current_buffer()
            .ok_or_else(|| signal("error", vec![Value::string("No current buffer")]))?;
        if super::editfns::buffer_read_only_active_in_state(obarray, dynamic, buf) {
            return Err(signal("buffer-read-only", vec![buf.name_value()]));
        }
        let (beg, end) = resolve_case_region_in_buffers(buffers, beg_val, end_val, args.get(2))?;
        let text = buf.buffer_substring_lisp_string(beg, end);
        (beg, end, text)
    };

    let replacement = transform(&text);
    if replacement == text {
        return Ok(Value::NIL);
    }

    replace_current_buffer_region_in_buffers(buffers, beg, end, &replacement, true)
}

fn casify_word_in_state(
    obarray: &Obarray,
    dynamic: &[OrderedRuntimeBindingMap],
    buffers: &mut crate::buffer::BufferManager,
    args: Vec<Value>,
    name: &str,
    transform: impl FnOnce(&LispString) -> LispString,
) -> EvalResult {
    expect_args(name, &args, 1)?;
    let n = expect_int(&args[0])?;

    let (beg, end, text, buffer_name, read_only) = {
        let buf = buffers
            .current_buffer()
            .ok_or_else(|| signal("error", vec![Value::string("No current buffer")]))?;
        let table = crate::emacs_core::syntax::SyntaxTable::for_buffer(buf);
        let pt = buf.point();
        let target = forward_word(buf, &table, n);
        let (beg, end) = if target >= pt {
            (pt, target)
        } else {
            (target, pt)
        };
        let text = buf.buffer_substring_lisp_string(beg, end);
        (
            beg,
            end,
            text,
            buf.name_value(),
            super::editfns::buffer_read_only_active_in_state(obarray, dynamic, buf),
        )
    };

    let replacement = transform(&text);
    if replacement == text {
        return Ok(Value::NIL);
    }
    if read_only {
        return Err(signal("buffer-read-only", vec![buffer_name]));
    }

    replace_current_buffer_region_in_buffers(buffers, beg, end, &replacement, false)
}

// ---------------------------------------------------------------------------
// Pure builtins
// ---------------------------------------------------------------------------

/// `(capitalize OBJ)` -- if OBJ is a string, capitalize the first letter
/// (uppercase first, lowercase rest).  If OBJ is a character, uppercase it.
pub(crate) fn builtin_capitalize(args: Vec<Value>) -> EvalResult {
    expect_args("capitalize", &args, 1)?;
    match args[0].kind() {
        ValueKind::String => {
            let string = args[0].as_lisp_string().expect("string");
            Ok(Value::heap_string(capitalize_lisp_string(string)))
        }
        ValueKind::Fixnum(c) => {
            let code = c as i64;
            Ok(Value::fixnum(upcase_char(code)))
        }
        other => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("char-or-string-p"), args[0]],
        )),
    }
}

/// Capitalize a string: uppercase the first letter of each word,
/// lowercase the rest.  A "word" starts after any non-alphanumeric character.
fn capitalize_string(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut new_word = true;
    for c in s.chars() {
        if c.is_alphanumeric() {
            if new_word {
                for u in titlecase_word_initial(c).chars() {
                    result.push(u);
                }
                new_word = false;
            } else {
                for l in c.to_lowercase() {
                    result.push(l);
                }
            }
        } else {
            result.push(c);
            new_word = true;
        }
    }
    result
}

/// `(upcase-initials OBJ)` -- uppercase the first letter of each word in
/// a string, leaving the rest unchanged.  For a char, uppercase it.
pub(crate) fn builtin_upcase_initials(args: Vec<Value>) -> EvalResult {
    expect_args("upcase-initials", &args, 1)?;
    match args[0].kind() {
        ValueKind::String => {
            let string = args[0].as_lisp_string().expect("string");
            Ok(Value::heap_string(upcase_initials_lisp_string(string)))
        }
        ValueKind::Fixnum(c) => {
            let code = c as i64;
            Ok(Value::fixnum(upcase_char(code)))
        }
        other => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("char-or-string-p"), args[0]],
        )),
    }
}

/// Uppercase the first letter of each word, leaving the rest unchanged.
pub(crate) fn upcase_initials_string(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut new_word = true;
    for c in s.chars() {
        if c.is_alphanumeric() {
            if new_word {
                for u in titlecase_word_initial(c).chars() {
                    result.push(u);
                }
                new_word = false;
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
            new_word = true;
        }
    }
    result
}

/// Classify the original matched text to decide whether to leave
/// REPLACEMENT as-is, upcase it entirely, or capitalize each word.
///
/// This is the backing logic for `replace-match`'s FIXEDCASE=nil
/// behavior. It mirrors GNU `src/search.c:2460-2525`, including the
/// `case-symbols-as-words` branch at search.c:2486/2495/2505.
///
/// `is_word_char` decides whether a character counts as a word
/// constituent for the "start of word" check. GNU consults the
/// buffer's syntax table (`SYNTAX(prevc) == Sword`) and, when
/// `case-symbols-as-words` is non-nil, also accepts `Ssymbol`. The
/// default closure below uses the standard syntax table defaults and
/// honors `case-symbols-as-words` via the supplied flag so that
/// callers who don't have a buffer handy still behave like GNU on
/// the standard table. Callers who do have a buffer handy should
/// pass a closure that consults `BVAR(current_buffer, syntax_table)`.
///
/// See audit findings #14 and #20 in `drafts/regex-search-audit.md`:
/// the old code used Rust's Unicode `is_alphanumeric()` and ignored
/// `case-symbols-as-words` entirely.
pub(crate) fn apply_replace_match_case(replacement: &str, matched: &str) -> String {
    apply_replace_match_case_with(replacement, matched, default_is_word_char)
}

/// Like `apply_replace_match_case`, but lets the caller supply the
/// predicate used for the "previous character is a word constituent"
/// check. Use this from paths that have a buffer syntax table in
/// scope so per-mode definitions of word constituents apply.
pub(crate) fn apply_replace_match_case_with<F>(
    replacement: &str,
    matched: &str,
    mut is_word_char: F,
) -> String
where
    F: FnMut(char) -> bool,
{
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum CaseAction {
        NoChange,
        AllCaps,
        CapInitial,
    }

    let mut some_multiletter_word = false;
    let mut some_lowercase = false;
    let mut some_uppercase = false;
    let mut some_nonuppercase_initial = false;
    let mut prev_is_word = false;

    for ch in matched.chars() {
        if ch.is_lowercase() {
            some_lowercase = true;
            if prev_is_word {
                some_multiletter_word = true;
            } else {
                some_nonuppercase_initial = true;
            }
        } else if ch.is_uppercase() {
            some_uppercase = true;
            if prev_is_word {
                some_multiletter_word = true;
            }
        } else if !prev_is_word {
            some_nonuppercase_initial = true;
        }

        prev_is_word = is_word_char(ch);
    }

    let case_action = if !some_lowercase && some_multiletter_word {
        CaseAction::AllCaps
    } else if !some_nonuppercase_initial && some_multiletter_word {
        CaseAction::CapInitial
    } else if !some_nonuppercase_initial && some_uppercase {
        CaseAction::AllCaps
    } else {
        CaseAction::NoChange
    };

    match case_action {
        CaseAction::NoChange => replacement.to_string(),
        CaseAction::AllCaps => replacement.to_uppercase(),
        CaseAction::CapInitial => upcase_initials_string(replacement),
    }
}

/// Default "is this a word constituent?" predicate for
/// `apply_replace_match_case`.
///
/// Mirrors GNU's standard syntax table: ASCII letters and digits are
/// `Sword`, `_` is `Ssymbol`, so `_` is not a word constituent in
/// the default baseline. Callers who want to honor
/// `case-symbols-as-words` or per-mode syntax tables should use
/// `apply_replace_match_case_with` with a closure that consults
/// `BVAR(current_buffer, syntax_table)`. See audit findings #14 and
/// #20 in `drafts/regex-search-audit.md`.
fn default_is_word_char(ch: char) -> bool {
    if ch.is_ascii_alphanumeric() {
        return true;
    }
    // GNU standard-syntax-table puts `$` and `%` in Sword. Neomacs's
    // `SyntaxTable::new_standard` agrees. Leave them inline here to
    // keep this hot path allocation-free.
    matches!(ch, '$' | '%')
}

pub(crate) fn builtin_downcase_region(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_region_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "downcase-region",
        downcase_lisp_string_emacs_compat,
    )
}

pub(crate) fn builtin_upcase_region(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_region_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "upcase-region",
        upcase_lisp_string_emacs_compat,
    )
}

pub(crate) fn builtin_capitalize_region(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_region_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "capitalize-region",
        capitalize_lisp_string,
    )
}

pub(crate) fn builtin_upcase_initials_region(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_region_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "upcase-initials-region",
        upcase_initials_lisp_string,
    )
}

pub(crate) fn builtin_downcase_word(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_word_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "downcase-word",
        downcase_lisp_string_emacs_compat,
    )
}

pub(crate) fn builtin_upcase_word(ctx: &mut super::eval::Context, args: Vec<Value>) -> EvalResult {
    casify_word_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "upcase-word",
        upcase_lisp_string_emacs_compat,
    )
}

pub(crate) fn builtin_capitalize_word(
    ctx: &mut super::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    casify_word_in_state(
        &ctx.obarray,
        &[],
        &mut ctx.buffers,
        args,
        "capitalize-word",
        capitalize_lisp_string,
    )
}

/// `(char-resolve-modifiers CHAR)` -- resolve modifier bits in character.
/// Resolve shift/control modifiers into the base character where possible.
pub(crate) fn builtin_char_resolve_modifiers(args: Vec<Value>) -> EvalResult {
    expect_args("char-resolve-modifiers", &args, 1)?;

    let code = match args[0].kind() {
        ValueKind::Fixnum(n) => n,
        other => {
            return Err(signal(
                "wrong-type-argument",
                vec![Value::symbol("fixnump"), args[0]],
            ));
        }
    };

    let modifiers = code & CHAR_MODIFIER_MASK;
    let mut base = code & !CHAR_MODIFIER_MASK;
    let mut remaining_mods = modifiers;

    if remaining_mods & CHAR_SHIFT != 0 {
        if base >= 'a' as i64 && base <= 'z' as i64 {
            base = base - 'a' as i64 + 'A' as i64;
            remaining_mods &= !CHAR_SHIFT;
        } else if base >= 'A' as i64 && base <= 'Z' as i64 {
            remaining_mods &= !CHAR_SHIFT;
        }
    }

    if remaining_mods & CHAR_CTL != 0 {
        if base >= '@' as i64 && base <= '_' as i64 {
            base &= 0x1F;
            remaining_mods &= !CHAR_CTL;
        } else if base >= 'a' as i64 && base <= 'z' as i64 {
            base &= 0x1F;
            remaining_mods &= !CHAR_CTL;
        } else if base == '?' as i64 {
            base = 127;
            remaining_mods &= !CHAR_CTL;
        }
    }

    Ok(Value::fixnum(base | remaining_mods))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "casefiddle_test.rs"]
mod tests;