copperlace 0.4.2

Procedural text renderer for generative grammar configuration
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
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
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::ptr;

use crate::config::{
    ruleset_from_file, ruleset_from_file_with_processors as load_file_with_processors,
    ruleset_from_str, ruleset_from_str_with_processors as load_str_with_processors,
};
use crate::render::{Processor, ProcessorRegistry, RenderContext, RenderOptions, RuleSet};

/// Status code for a successful C ABI call.
pub const COPPERLACE_OK: c_int = 0;
/// Status code for invalid C ABI arguments such as null required pointers.
pub const COPPERLACE_INVALID_ARGUMENT: c_int = 1;
/// Status code for config loading, parsing, or compilation failures.
pub const COPPERLACE_PARSE_ERROR: c_int = 2;
/// Status code for rule rendering failures.
pub const COPPERLACE_RENDER_ERROR: c_int = 3;

/// Host callback used by custom C ABI processors.
///
/// The callback receives a UTF-8 input string, an opaque result handle, and the
/// user data pointer provided when creating the ruleset. It should set either
/// output or error on `result` and return [`COPPERLACE_OK`] on success.
pub type CopperlaceProcessorCallback =
    unsafe extern "C" fn(*const c_char, *mut CopperlaceProcessorResult, *mut c_void) -> c_int;

/// Opaque C ABI handle for a compiled Copperlace ruleset.
///
/// Handles are allocated by `copperlace_ruleset_from_file` or
/// `copperlace_ruleset_from_string` and must be released with
/// `copperlace_ruleset_free`.
pub struct CopperlaceRuleSet {
    ruleset: RuleSet,
}

/// Opaque C ABI result handle passed to custom processor callbacks.
pub struct CopperlaceProcessorResult {
    output: Option<String>,
    error: Option<String>,
}

struct CallbackProcessor {
    callback: CopperlaceProcessorCallback,
    user_data: *mut c_void,
}

unsafe impl Send for CallbackProcessor {}
unsafe impl Sync for CallbackProcessor {}

impl Processor for CallbackProcessor {
    fn process(&self, value: &str) -> Result<String, String> {
        let input =
            CString::new(value).map_err(|_| "processor input contains an interior NUL byte")?;
        let mut result = CopperlaceProcessorResult {
            output: None,
            error: None,
        };
        let status = unsafe { (self.callback)(input.as_ptr(), &mut result, self.user_data) };

        if let Some(error) = result.error {
            return Err(error);
        }
        if status != COPPERLACE_OK {
            return Err(format!("processor callback failed with status {status}"));
        }
        result
            .output
            .ok_or_else(|| "processor callback did not set output".to_string())
    }
}

/// Loads a configuration file and returns an opaque ruleset handle.
///
/// On success, writes a non-null handle to `out_handle` and returns
/// [`COPPERLACE_OK`]. On failure, writes null to `out_handle`, writes an owned
/// error string to `out_error` when provided, and returns a nonzero status code.
/// Returned error strings must be released with `copperlace_string_free`.
///
/// # Safety
///
/// `path` must point to a valid NUL-terminated UTF-8 string. `out_handle` must
/// be a valid writable pointer when non-null. `out_error` must be valid for
/// writing when non-null, and any returned error string must be released with
/// [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_from_file(
    path: *const c_char,
    out_handle: *mut *mut CopperlaceRuleSet,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);

    let Some(path) = read_c_string(path, out_error) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };

    match ruleset_from_file(path) {
        Ok(ruleset) => write_handle(ruleset, out_handle, out_error),
        Err(error) => {
            write_null_handle(out_handle);
            write_out_string(out_error, &error.to_string());
            COPPERLACE_PARSE_ERROR
        }
    }
}

/// Loads a configuration file and returns a ruleset handle with custom processors.
///
/// # Safety
///
/// `path` must point to a valid NUL-terminated UTF-8 string. When
/// `processor_len` is nonzero, `processor_names`, `processor_callbacks`, and
/// `processor_user_data` must each point to arrays with at least
/// `processor_len` entries. Processor names must point to valid NUL-terminated
/// UTF-8 strings. `out_handle` must be a valid writable pointer when non-null.
/// `out_error` must be valid for writing when non-null, and any returned error
/// string must be released with [`copperlace_string_free`]. Processor callbacks
/// and user data must remain valid until the returned ruleset handle is freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_from_file_with_processors(
    path: *const c_char,
    processor_names: *const *const c_char,
    processor_callbacks: *const Option<CopperlaceProcessorCallback>,
    processor_user_data: *const *mut c_void,
    processor_len: usize,
    out_handle: *mut *mut CopperlaceRuleSet,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);

    let Some(path) = read_c_string(path, out_error) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };
    let Some(processors) = read_processors(
        processor_names,
        processor_callbacks,
        processor_user_data,
        processor_len,
        out_error,
    ) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };

    match load_file_with_processors(path, processors) {
        Ok(ruleset) => write_handle(ruleset, out_handle, out_error),
        Err(error) => {
            write_null_handle(out_handle);
            write_out_string(out_error, &error.to_string());
            COPPERLACE_PARSE_ERROR
        }
    }
}

/// Compiles a configuration string and returns an opaque ruleset handle.
///
/// On success, writes a non-null handle to `out_handle` and returns
/// [`COPPERLACE_OK`]. On failure, writes null to `out_handle`, writes an owned
/// error string to `out_error` when provided, and returns a nonzero status code.
/// Returned error strings must be released with `copperlace_string_free`.
///
/// # Safety
///
/// `config` must point to a valid NUL-terminated UTF-8 string. `out_handle`
/// must be a valid writable pointer when non-null. `out_error` must be valid
/// for writing when non-null, and any returned error string must be released
/// with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_from_string(
    config: *const c_char,
    out_handle: *mut *mut CopperlaceRuleSet,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);

    let Some(config) = read_c_string(config, out_error) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };

    match ruleset_from_str(&config) {
        Ok(ruleset) => write_handle(ruleset, out_handle, out_error),
        Err(error) => {
            write_null_handle(out_handle);
            write_out_string(out_error, &error.to_string());
            COPPERLACE_PARSE_ERROR
        }
    }
}

/// Compiles a configuration string and returns a ruleset handle with custom processors.
///
/// # Safety
///
/// `config` must point to a valid NUL-terminated UTF-8 string. When
/// `processor_len` is nonzero, `processor_names`, `processor_callbacks`, and
/// `processor_user_data` must each point to arrays with at least
/// `processor_len` entries. Processor names must point to valid NUL-terminated
/// UTF-8 strings. `out_handle` must be a valid writable pointer when non-null.
/// `out_error` must be valid for writing when non-null, and any returned error
/// string must be released with [`copperlace_string_free`]. Processor callbacks
/// and user data must remain valid until the returned ruleset handle is freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_from_string_with_processors(
    config: *const c_char,
    processor_names: *const *const c_char,
    processor_callbacks: *const Option<CopperlaceProcessorCallback>,
    processor_user_data: *const *mut c_void,
    processor_len: usize,
    out_handle: *mut *mut CopperlaceRuleSet,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);

    let Some(config) = read_c_string(config, out_error) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };
    let Some(processors) = read_processors(
        processor_names,
        processor_callbacks,
        processor_user_data,
        processor_len,
        out_error,
    ) else {
        write_null_handle(out_handle);
        return COPPERLACE_INVALID_ARGUMENT;
    };

    match load_str_with_processors(&config, processors) {
        Ok(ruleset) => write_handle(ruleset, out_handle, out_error),
        Err(error) => {
            write_null_handle(out_handle);
            write_out_string(out_error, &error.to_string());
            COPPERLACE_PARSE_ERROR
        }
    }
}

/// Sets the output for a custom processor callback result.
///
/// # Safety
///
/// `result` must be the valid result handle passed to the active processor
/// callback. `value` must point to a valid NUL-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_processor_result_set_output(
    result: *mut CopperlaceProcessorResult,
    value: *const c_char,
) -> c_int {
    if result.is_null() {
        return COPPERLACE_INVALID_ARGUMENT;
    }
    let Some(value) = read_c_string(value, ptr::null_mut()) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };
    unsafe {
        (*result).output = Some(value);
    }
    COPPERLACE_OK
}

/// Sets the error for a custom processor callback result.
///
/// # Safety
///
/// `result` must be the valid result handle passed to the active processor
/// callback. `message` must point to a valid NUL-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_processor_result_set_error(
    result: *mut CopperlaceProcessorResult,
    message: *const c_char,
) -> c_int {
    if result.is_null() {
        return COPPERLACE_INVALID_ARGUMENT;
    }
    let Some(message) = read_c_string(message, ptr::null_mut()) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };
    unsafe {
        (*result).error = Some(message);
    }
    COPPERLACE_OK
}

/// Renders a named rule from a ruleset handle.
///
/// On success, writes an owned UTF-8 string to `out_string` and returns
/// [`COPPERLACE_OK`]. On failure, writes null to `out_string`, writes an owned
/// error string to `out_error` when provided, and returns a nonzero status code.
/// Returned output and error strings must be released with
/// `copperlace_string_free`.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. `out_string` and `out_error`
/// must be valid for writing when non-null. Any returned output or error string
/// must be released with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_with_context(
            handle,
            rule,
            ptr::null(),
            ptr::null(),
            0,
            out_string,
            out_error,
        )
    }
}

/// Renders a named rule from a ruleset handle with initial context values.
///
/// `context_keys` and `context_values` are parallel arrays of UTF-8 C strings.
/// They may be null only when `context_len` is zero. Duplicate keys are allowed;
/// later entries replace earlier entries.
///
/// On success, writes an owned UTF-8 string to `out_string` and returns
/// [`COPPERLACE_OK`]. On failure, writes null to `out_string`, writes an owned
/// error string to `out_error` when provided, and returns a nonzero status code.
/// Returned output and error strings must be released with
/// `copperlace_string_free`.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_string` and `out_error` must be valid for
/// writing when non-null. Any returned output or error string must be released
/// with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_with_context(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_with_context_and_options(
            handle,
            rule,
            context_keys,
            context_values,
            context_len,
            0,
            out_string,
            out_error,
        )
    }
}

/// Renders a named rule from a ruleset handle with initial context values and render options.
///
/// `max_recursion_depth` controls recursive rule expansion. A value of zero
/// preserves default circular-reference errors. Values greater than zero allow
/// that many recursive re-entries before recursive calls return an empty string.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_string` and `out_error` must be valid for
/// writing when non-null. Any returned output or error string must be released
/// with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_with_context_and_options(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    max_recursion_depth: usize,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);
    write_null_string(out_string);

    if handle.is_null() {
        write_out_string(out_error, "ruleset handle is null");
        return COPPERLACE_INVALID_ARGUMENT;
    }

    let Some(rule) = read_c_string(rule, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };
    let Some(context) = read_context(context_keys, context_values, context_len, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };

    let ruleset = unsafe { &(*handle).ruleset };
    let options = RenderOptions {
        max_recursion_depth,
    };
    match ruleset.render_rule_with_context_and_options(&rule, context, options) {
        Ok(output) => {
            if write_out_string(out_string, &output) {
                COPPERLACE_OK
            } else {
                write_out_string(out_error, "output string contains an interior NUL byte");
                COPPERLACE_RENDER_ERROR
            }
        }
        Err(error) => {
            write_out_string(out_error, &error.to_string());
            COPPERLACE_RENDER_ERROR
        }
    }
}

/// Renders a named rule, inferring formatted structured JSON for object-valued rules.
///
/// String-valued and list-valued rules use existing text rendering. Object-valued
/// rules return formatted JSON using tab indentation.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. `out_string` and `out_error`
/// must be valid for writing when non-null. Any returned output or error string
/// must be released with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_inferred(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_inferred_with_context(
            handle,
            rule,
            ptr::null(),
            ptr::null(),
            0,
            out_string,
            out_error,
        )
    }
}

/// Renders a named rule with initial context, inferring formatted structured JSON for object-valued rules.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_string` and `out_error` must be valid for
/// writing when non-null. Any returned output or error string must be released
/// with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_inferred_with_context(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_inferred_with_context_and_options(
            handle,
            rule,
            context_keys,
            context_values,
            context_len,
            0,
            out_string,
            out_error,
        )
    }
}

/// Renders a named rule with initial context and render options, inferring formatted structured JSON for object-valued rules.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_string` and `out_error` must be valid for
/// writing when non-null. Any returned output or error string must be released
/// with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_inferred_with_context_and_options(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    max_recursion_depth: usize,
    out_string: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);
    write_null_string(out_string);

    if handle.is_null() {
        write_out_string(out_error, "ruleset handle is null");
        return COPPERLACE_INVALID_ARGUMENT;
    }

    let Some(rule) = read_c_string(rule, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };
    let Some(context) = read_context(context_keys, context_values, context_len, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };

    let ruleset = unsafe { &(*handle).ruleset };
    let options = RenderOptions {
        max_recursion_depth,
    };
    match ruleset.render_rule_inferred_with_context_and_options(&rule, context, options) {
        Ok(output) => {
            if write_out_string(out_string, &output) {
                COPPERLACE_OK
            } else {
                write_out_string(out_error, "output string contains an interior NUL byte");
                COPPERLACE_RENDER_ERROR
            }
        }
        Err(error) => {
            write_out_string(out_error, &error.to_string());
            COPPERLACE_RENDER_ERROR
        }
    }
}

/// Renders a named structured rule from a ruleset handle as JSON text.
///
/// On success, writes an owned UTF-8 JSON string to `out_json` and returns
/// [`COPPERLACE_OK`]. When `format_json` is false, the JSON is compact. When
/// true, it is formatted with tab indentation. On failure, writes null to
/// `out_json`, writes an owned error string to `out_error` when provided, and
/// returns a nonzero status code. Returned output and error strings must be
/// released with `copperlace_string_free`.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. `out_json` must be a valid
/// writable pointer. `out_error` must be valid for writing when non-null. Any
/// returned output or error string must be released with
/// [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_structured_json(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    format_json: bool,
    out_json: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_structured_json_with_context(
            handle,
            rule,
            ptr::null(),
            ptr::null(),
            0,
            format_json,
            out_json,
            out_error,
        )
    }
}

/// Renders a named structured rule from a ruleset handle with initial context.
///
/// `context_keys` and `context_values` are parallel arrays of UTF-8 C strings.
/// They may be null only when `context_len` is zero. Duplicate keys are allowed;
/// later entries replace earlier entries.
///
/// On success, writes an owned UTF-8 JSON string to `out_json` and returns
/// [`COPPERLACE_OK`]. When `format_json` is false, the JSON is compact. When
/// true, it is formatted with tab indentation. On failure, writes null to
/// `out_json`, writes an owned error string to `out_error` when provided, and
/// returns a nonzero status code. Returned output and error strings must be
/// released with `copperlace_string_free`.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_json` must be a valid writable pointer.
/// `out_error` must be valid for writing when non-null. Any returned output or
/// error string must be released with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_structured_json_with_context(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    format_json: bool,
    out_json: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    unsafe {
        copperlace_ruleset_render_structured_json_with_context_and_options(
            handle,
            rule,
            context_keys,
            context_values,
            context_len,
            format_json,
            0,
            out_json,
            out_error,
        )
    }
}

/// Renders a named structured rule from a ruleset handle with initial context and render options.
///
/// # Safety
///
/// `handle` must be a live ruleset handle returned by Copperlace. `rule` must
/// point to a valid NUL-terminated UTF-8 string. When `context_len` is nonzero,
/// `context_keys` and `context_values` must each point to arrays with at least
/// `context_len` entries, and every entry must point to a valid
/// NUL-terminated UTF-8 string. `out_json` must be a valid writable pointer.
/// `out_error` must be valid for writing when non-null. Any returned output or
/// error string must be released with [`copperlace_string_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_render_structured_json_with_context_and_options(
    handle: *const CopperlaceRuleSet,
    rule: *const c_char,
    context_keys: *const *const c_char,
    context_values: *const *const c_char,
    context_len: usize,
    format_json: bool,
    max_recursion_depth: usize,
    out_json: *mut *mut c_char,
    out_error: *mut *mut c_char,
) -> c_int {
    clear_out_error(out_error);

    if out_json.is_null() {
        write_out_string(out_error, "out_json is null");
        return COPPERLACE_INVALID_ARGUMENT;
    }
    write_null_string(out_json);

    if handle.is_null() {
        write_out_string(out_error, "ruleset handle is null");
        return COPPERLACE_INVALID_ARGUMENT;
    }

    let Some(rule) = read_c_string(rule, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };
    let Some(context) = read_context(context_keys, context_values, context_len, out_error) else {
        return COPPERLACE_INVALID_ARGUMENT;
    };

    let ruleset = unsafe { &(*handle).ruleset };
    let options = RenderOptions {
        max_recursion_depth,
    };
    let json = ruleset
        .render_rule_structured_with_context_and_options(&rule, context, options)
        .and_then(|value| {
            if format_json {
                value.to_formatted_json()
            } else {
                value.to_compact_json()
            }
        });

    match json {
        Ok(output) => {
            if write_out_string(out_json, &output) {
                COPPERLACE_OK
            } else {
                write_out_string(out_error, "structured JSON contains an interior NUL byte");
                COPPERLACE_RENDER_ERROR
            }
        }
        Err(error) => {
            write_out_string(out_error, &error.to_string());
            COPPERLACE_RENDER_ERROR
        }
    }
}

fn read_context(
    keys: *const *const c_char,
    values: *const *const c_char,
    len: usize,
    out_error: *mut *mut c_char,
) -> Option<RenderContext> {
    let mut context = RenderContext::new();
    if len == 0 {
        return Some(context);
    }
    if keys.is_null() {
        write_out_string(out_error, "context keys array is null");
        return None;
    }
    if values.is_null() {
        write_out_string(out_error, "context values array is null");
        return None;
    }

    for index in 0..len {
        let key_ptr = unsafe { *keys.add(index) };
        let value_ptr = unsafe { *values.add(index) };
        let key = read_c_string(key_ptr, out_error)?;
        let value = read_c_string(value_ptr, out_error)?;
        context.insert(key, value);
    }

    Some(context)
}

fn read_processors(
    names: *const *const c_char,
    callbacks: *const Option<CopperlaceProcessorCallback>,
    user_data: *const *mut c_void,
    len: usize,
    out_error: *mut *mut c_char,
) -> Option<ProcessorRegistry> {
    let mut processors = ProcessorRegistry::new();
    if len == 0 {
        return Some(processors);
    }
    if names.is_null() {
        write_out_string(out_error, "processor names array is null");
        return None;
    }
    if callbacks.is_null() {
        write_out_string(out_error, "processor callbacks array is null");
        return None;
    }
    if user_data.is_null() {
        write_out_string(out_error, "processor user data array is null");
        return None;
    }

    for index in 0..len {
        let name_ptr = unsafe { *names.add(index) };
        let callback = unsafe { *callbacks.add(index) };
        let Some(callback) = callback else {
            write_out_string(out_error, "processor callback is null");
            return None;
        };
        let name = read_c_string(name_ptr, out_error)?;
        let user_data = unsafe { *user_data.add(index) };
        processors.insert(
            name,
            std::sync::Arc::new(CallbackProcessor {
                callback,
                user_data,
            }),
        );
    }

    Some(processors)
}

/// Releases a ruleset handle returned by the C ABI.
///
/// Passing null is allowed and has no effect.
///
/// # Safety
///
/// `handle` must be null or a handle previously returned by Copperlace that has
/// not already been freed. After this call, the handle must not be used again.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_ruleset_free(handle: *mut CopperlaceRuleSet) {
    if !handle.is_null() {
        unsafe {
            drop(Box::from_raw(handle));
        }
    }
}

/// Releases a string returned by the C ABI.
///
/// Passing null is allowed and has no effect.
///
/// # Safety
///
/// `value` must be null or a string pointer previously returned by Copperlace
/// that has not already been freed. After this call, the pointer must not be
/// used again.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn copperlace_string_free(value: *mut c_char) {
    if !value.is_null() {
        unsafe {
            drop(CString::from_raw(value));
        }
    }
}

fn read_c_string(value: *const c_char, out_error: *mut *mut c_char) -> Option<String> {
    if value.is_null() {
        write_out_string(out_error, "input string is null");
        return None;
    }

    match unsafe { CStr::from_ptr(value) }.to_str() {
        Ok(value) => Some(value.to_string()),
        Err(error) => {
            write_out_string(
                out_error,
                &format!("input string is not valid UTF-8: {error}"),
            );
            None
        }
    }
}

fn write_handle(
    ruleset: RuleSet,
    out_handle: *mut *mut CopperlaceRuleSet,
    out_error: *mut *mut c_char,
) -> c_int {
    if out_handle.is_null() {
        write_out_string(out_error, "out_handle is null");
        return COPPERLACE_INVALID_ARGUMENT;
    }

    let handle = Box::into_raw(Box::new(CopperlaceRuleSet { ruleset }));
    unsafe {
        *out_handle = handle;
    }
    COPPERLACE_OK
}

fn write_null_handle(out_handle: *mut *mut CopperlaceRuleSet) {
    if !out_handle.is_null() {
        unsafe {
            *out_handle = ptr::null_mut();
        }
    }
}

fn write_null_string(out_string: *mut *mut c_char) {
    if !out_string.is_null() {
        unsafe {
            *out_string = ptr::null_mut();
        }
    }
}

fn clear_out_error(out_error: *mut *mut c_char) {
    write_null_string(out_error);
}

fn write_out_string(out_string: *mut *mut c_char, value: &str) -> bool {
    if out_string.is_null() {
        return true;
    }

    let Ok(value) = CString::new(value) else {
        return false;
    };

    unsafe {
        *out_string = value.into_raw();
    }
    true
}