alef 0.83.0

Opinionated polyglot binding generator for Rust libraries
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
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Grammar validation for cross-language publish/namespace coordinates.
//!
//! Each target ecosystem has its own coordinate grammar (a Maven groupId is not a Java
//! package; a NuGet package ID is not a C# namespace; a SwiftPM module name is not a
//! package name). This module validates each grammar separately so a backend can never
//! silently reuse one coordinate's rules -- or another coordinate's value -- for a
//! different one. See the `centralized-naming` rule: casing lives in `naming.rs`, but
//! coordinate *grammar* validation is centralized here for the same reason.
//!
//! Every validator accepts every value a currently-working default configuration would
//! produce; only explicit, out-of-grammar user input is rejected.

use crate::codegen::identifier_grammar::{
    is_csharp_identifier_part, is_csharp_identifier_start, is_java_identifier_part, is_java_identifier_start,
    is_kotlin_identifier_part, is_kotlin_identifier_start, is_swift_identifier_part, is_swift_identifier_start,
};

/// Java reserved keywords and literals (JLS SE 21 §3.9, §3.10.3, §3.10.7) that cannot
/// appear as an `Identifier`, and therefore cannot appear as a package-name segment
/// (JLS §7.4.1: `PackageName: Identifier | PackageName . Identifier`). Restricted
/// identifiers such as `var`, `yield`, `record`, `sealed`, and `permits` are
/// deliberately NOT listed: the JLS still permits them as ordinary identifiers outside
/// their restricted syntactic positions, so rejecting them here would reject valid
/// package names.
const JAVA_RESERVED: &[&str] = &[
    "abstract",
    "assert",
    "boolean",
    "break",
    "byte",
    "case",
    "catch",
    "char",
    "class",
    "const",
    "continue",
    "default",
    "do",
    "double",
    "else",
    "enum",
    "extends",
    "final",
    "finally",
    "float",
    "for",
    "goto",
    "if",
    "implements",
    "import",
    "instanceof",
    "int",
    "interface",
    "long",
    "native",
    "new",
    "package",
    "private",
    "protected",
    "public",
    "return",
    "short",
    "static",
    "strictfp",
    "super",
    "switch",
    "synchronized",
    "this",
    "throw",
    "throws",
    "transient",
    "try",
    "void",
    "volatile",
    "while",
    "true",
    "false",
    "null",
    // `_` is a keyword as of Java 9 (JLS SE 21 3.9) even though
    // `Character.isJavaIdentifierStart('_')` is true, so the character grammar cannot catch it.
    // Confirmed against javac 25.0.2: `package probe._;` fails, `package probe._core;` compiles.
    // C# has no equivalent rule -- `namespace Probe._` compiles under dotnet 10.0.100. ~keep
    "_",
];

/// Kotlin hard keywords (kotlinlang.org/docs/keyword-reference.html "Hard keywords") that
/// cannot be used as an identifier without backtick-escaping. A JVM package emitted by
/// alef also carries the Kotlin/Kotlin-Android facade, so a package segment must be a
/// valid identifier in both languages. Soft and modifier keywords (e.g. `by`,
/// `constructor`, `data`) are intentionally excluded: Kotlin permits them unescaped.
const KOTLIN_HARD_KEYWORDS: &[&str] = &[
    "as",
    "break",
    "class",
    "continue",
    "do",
    "else",
    "false",
    "for",
    "fun",
    "if",
    "in",
    "interface",
    "is",
    "null",
    "object",
    "package",
    "return",
    "super",
    "this",
    "throw",
    "true",
    "try",
    "typealias",
    "typeof",
    "val",
    "var",
    "when",
    "while",
];

/// The identifier grammar one dot-separated coordinate segment must satisfy. A Java package, a
/// Kotlin package, and a C# namespace share this shape -- `Identifier ('.' Identifier)*` -- but
/// each admits a *different* set of characters, so the character classes are supplied per
/// language rather than approximated by one shared pair of predicates.
struct SegmentGrammar {
    language: &'static str,
    is_start: fn(char) -> bool,
    is_part: fn(char) -> bool,
    start_hint: &'static str,
    reserved: &'static [&'static str],
}

/// A Java package segment, minus the ISO control characters `Character.isJavaIdentifierPart`
/// accepts.
///
/// The JLS really does admit those 56 code points inside an identifier, and
/// [`is_java_identifier_part`] mirrors that exactly. A *coordinate* is additionally spliced into
/// `pom.xml`, `build.gradle.kts`, and filesystem paths, where an invisible control character is
/// a spoofing vector that no working default configuration can produce, so coordinate validation
/// is deliberately stricter than the JLS on this one point. ~keep
fn is_java_package_part(character: char) -> bool {
    is_java_identifier_part(character) && !character.is_control()
}

const JAVA_SEGMENT_GRAMMAR: SegmentGrammar = SegmentGrammar {
    language: "Java",
    is_start: is_java_identifier_start,
    is_part: is_java_package_part,
    start_hint: "a letter, or a currency (`$`) or connector (`_`) character",
    reserved: JAVA_RESERVED,
};

/// Kotlin's own lexer accepts a narrower set than Java or C#: measured against `kotlinc` 2.4.10
/// (see `codegen::identifier_grammar` and
/// `tests/identifier_grammar_compiler_oracle.rs::kotlinc_agrees_with_validate_kotlin_package`,
/// which invokes `kotlinc` as a subprocess on every run), a Kotlin identifier starts with
/// `Lu|Ll|Lt|Lm|Lo` or a literal `_` and continues with those plus `Nd`, rejecting `Nl` and every
/// mark/format category that Java and C# both admit inside an identifier.
const KOTLIN_SEGMENT_GRAMMAR: SegmentGrammar = SegmentGrammar {
    language: "Kotlin",
    is_start: is_kotlin_identifier_start,
    is_part: is_kotlin_identifier_part,
    start_hint: "a letter (not a letter-number such as a Roman numeral) or `_`",
    reserved: KOTLIN_HARD_KEYWORDS,
};

fn validate_package_segments(name: &str, grammar: &SegmentGrammar) -> Result<(), String> {
    if name.is_empty() {
        return Err("must not be empty".to_string());
    }
    for segment in name.split('.') {
        validate_one_segment(name, segment, grammar)?;
    }
    Ok(())
}

fn validate_one_segment(name: &str, segment: &str, grammar: &SegmentGrammar) -> Result<(), String> {
    let language = grammar.language;
    if segment.is_empty() {
        return Err(format!("`{name}` has an empty segment (leading/trailing/double dot)"));
    }
    let mut chars = segment.chars();
    let first = chars.next().expect("segment is non-empty");
    if !(grammar.is_start)(first) {
        return Err(format!(
            "segment `{segment}` in `{name}` must start with {}",
            grammar.start_hint
        ));
    }
    if let Some(bad) = chars.find(|character| !(grammar.is_part)(*character)) {
        return Err(format!(
            "segment `{segment}` in `{name}` contains `{bad}`, which is not a valid {language} identifier character"
        ));
    }
    if grammar.reserved.contains(&segment) {
        return Err(format!(
            "segment `{segment}` in `{name}` is a {language} reserved word and cannot be used unescaped"
        ));
    }
    Ok(())
}

/// Validate a Java package name using the JLS identifier grammar (JLS SE 21 3.8, 7.4.1), as
/// implemented by `Character.isJavaIdentifierStart`/`isJavaIdentifierPart`. Java keywords are
/// case-sensitive, and `$` is legal because it is a currency symbol -- as is every other
/// currency symbol, and every connector punctuation character.
pub fn validate_java_package(name: &str) -> Result<(), String> {
    validate_package_segments(name, &JAVA_SEGMENT_GRAMMAR)
}

/// Validate a Kotlin package name as it is emitted in Kotlin source. Kotlin keywords are
/// case-sensitive and `$` is not accepted in an unescaped source identifier.
pub fn validate_kotlin_package(name: &str) -> Result<(), String> {
    validate_package_segments(name, &KOTLIN_SEGMENT_GRAMMAR)
}

/// Validate a Maven `groupId` or `artifactId`. Maven Central's component validation
/// (Sonatype OSSRH publishing requirements) restricts both to ASCII letters, digits,
/// `.`, `_`, and `-`, since they become repository path segments; `..` or a leading/
/// trailing `.`/`-`/`/` would let a coordinate escape its repository directory. This is
/// deliberately more permissive than [`validate_java_package`] (Maven groupIds commonly
/// contain hyphens, e.g. `io.projectreactor.netty`) and deliberately ASCII-only (Maven
/// Central coordinates are conventionally ASCII; unlike a JVM package name, there is no
/// widely-interoperable non-ASCII Maven coordinate convention to preserve).
pub fn validate_maven_coordinate(field: &str, value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err(format!("{field} must not be empty"));
    }
    if value.contains("..") || value.contains('/') || value.contains('\\') {
        return Err(format!(
            "{field} `{value}` must not contain `..`, `/`, or `\\` (Maven coordinates become repository path segments)"
        ));
    }
    if value.starts_with('.') || value.starts_with('-') || value.ends_with('.') || value.ends_with('-') {
        return Err(format!("{field} `{value}` must not start or end with `.` or `-`"));
    }
    if let Some(bad) = value
        .chars()
        .find(|c| !(c.is_ascii_alphanumeric() || *c == '.' || *c == '_' || *c == '-'))
    {
        return Err(format!(
            "{field} `{value}` contains `{bad}`; Maven coordinates allow only ASCII letters, digits, `.`, `_`, and `-`"
        ));
    }
    Ok(())
}

/// ~keep NuGet package ID characters, per `NuGet.Packaging.PackageIdValidator`'s
/// `^\w+([_.-]\w+)*$` grammar. The pinned Unicode category table gives `\w` the .NET set:
/// letters, nonspacing marks, decimal digits, and connector punctuation. Callers must also
/// check case-insensitive collisions across a workspace.
pub fn validate_nuget_package_id(value: &str) -> Result<(), String> {
    if value.is_empty() {
        return Err("NuGet package ID must not be empty".to_string());
    }
    if value.encode_utf16().count() > 100 {
        return Err(format!(
            "NuGet package ID `{value}` exceeds the 100 UTF-16 code-unit limit"
        ));
    }
    if value.starts_with(['.', '-']) || value.ends_with(['.', '-']) {
        return Err(format!(
            "NuGet package ID `{value}` must not start or end with `.` or `-`"
        ));
    }
    if let Some(character) = value.chars().find(|character| character.len_utf16() != 1) {
        return Err(format!(
            "NuGet package ID `{value}` contains supplementary character `{character}`; NuGet's .NET regex evaluates UTF-16 code units and rejects surrogate pairs"
        ));
    }
    if let Some(bad) = value
        .chars()
        .find(|character| !is_dotnet_word_character(*character) && !matches!(character, '.' | '-'))
    {
        return Err(format!(
            "NuGet package ID `{value}` contains `{bad}`; allowed characters are .NET word characters, `.`, and `-`"
        ));
    }
    if value
        .as_bytes()
        .windows(2)
        .any(|pair| matches!(pair, [b'.' | b'-', b'.' | b'-']))
    {
        return Err(format!(
            "NuGet package ID `{value}` must have a letter, digit, or `_` between `.`/`-` separators"
        ));
    }
    Ok(())
}

/// Fold a NuGet package ID into the collision key `validate_nuget_package_id`'s doc comment
/// promises callers will check across a workspace ("Callers must also check case-insensitive
/// collisions"): NuGet.org's own `PackageIdComparer` treats package IDs as
/// `StringComparer.OrdinalIgnoreCase`, so two crates publishing `MyLib` and `mylib` would
/// collide on the real registry even though they differ under a plain `==`.
///
/// This maps each character through ICU's simple uppercase table, matching .NET's ICU-backed
/// `OrdinalCasing.ToUpper` one-code-point mapping. A non-ASCII character is never allowed to map
/// onto ASCII: .NET's ordinal fast path explicitly keeps those domains unequal (`ſ` != `S`,
/// `K` != `K`).
pub fn nuget_ordinal_fold(value: &str) -> String {
    let mapper = icu_casemap::CaseMapper::new();
    value
        .chars()
        .map(|character| {
            let uppercase = mapper.simple_uppercase(character);
            if !character.is_ascii() && uppercase.is_ascii() {
                character
            } else {
                uppercase
            }
        })
        .collect()
}

fn is_dotnet_word_character(character: char) -> bool {
    use unicode_general_category::{GeneralCategory, get_general_category};

    matches!(
        get_general_category(character),
        GeneralCategory::LowercaseLetter
            | GeneralCategory::UppercaseLetter
            | GeneralCategory::TitlecaseLetter
            | GeneralCategory::OtherLetter
            | GeneralCategory::ModifierLetter
            | GeneralCategory::NonspacingMark
            | GeneralCategory::DecimalNumber
            | GeneralCategory::ConnectorPunctuation
    )
}

/// C# reserved keywords (ECMA-334 §6.4.3 / C# language specification, "Keywords") that
/// cannot appear as an `available_identifier`. A verbatim identifier (`@class`) can
/// escape a keyword, but alef does not emit verbatim identifiers for a generated
/// namespace, so a reserved word here would be a syntax error in the emitted source.
const CSHARP_RESERVED: &[&str] = &[
    "abstract",
    "as",
    "base",
    "bool",
    "break",
    "byte",
    "case",
    "catch",
    "char",
    "checked",
    "class",
    "const",
    "continue",
    "decimal",
    "default",
    "delegate",
    "do",
    "double",
    "else",
    "enum",
    "event",
    "explicit",
    "extern",
    "false",
    "finally",
    "fixed",
    "float",
    "for",
    "foreach",
    "goto",
    "if",
    "implicit",
    "in",
    "int",
    "interface",
    "internal",
    "is",
    "lock",
    "long",
    "namespace",
    "new",
    "null",
    "object",
    "operator",
    "out",
    "override",
    "params",
    "private",
    "protected",
    "public",
    "readonly",
    "ref",
    "return",
    "sbyte",
    "sealed",
    "short",
    "sizeof",
    "stackalloc",
    "static",
    "string",
    "struct",
    "switch",
    "this",
    "throw",
    "true",
    "try",
    "typeof",
    "uint",
    "ulong",
    "unchecked",
    "unsafe",
    "ushort",
    "using",
    "virtual",
    "void",
    "volatile",
    "while",
];

const CSHARP_SEGMENT_GRAMMAR: SegmentGrammar = SegmentGrammar {
    language: "C#",
    is_start: is_csharp_identifier_start,
    is_part: is_csharp_identifier_part,
    start_hint: "a letter or `_`",
    reserved: CSHARP_RESERVED,
};

/// Validate a C# namespace: dot-separated identifiers per the C# language specification's
/// `qualified_identifier`, each an `identifier` under ECMA-334 6.4.3 and none of which is a
/// reserved keyword. Unicode letters are accepted, so `München.Parser` is a legal namespace.
///
/// This is *not* the Java package grammar with different keywords. Two differences bite:
/// a currency symbol starts a Java identifier but not a C# one, and Roslyn lexes UTF-16 code
/// units, so a supplementary-plane letter that `javac` accepts is a `CS1056` under `dotnet`.
/// Both are enforced by [`is_csharp_identifier_start`]/[`is_csharp_identifier_part`].
pub fn validate_csharp_namespace(name: &str) -> Result<(), String> {
    validate_package_segments(name, &CSHARP_SEGMENT_GRAMMAR)
}

/// Swift reserved keywords (Swift Language Reference, "Lexical Structure > Keywords and
/// Punctuation", swift.org/documentation) that require backtick-escaping to use as an
/// identifier. Swift keywords are case-sensitive -- `class` is reserved but `Class` is an
/// ordinary identifier (confirmed against `swiftc` 6.3.1: `struct Class { ... }` compiles) --
/// so this list must be compared against the input as-is, never lowercased first.
const SWIFT_RESERVED: &[&str] = &[
    "associatedtype",
    "class",
    "deinit",
    "enum",
    "extension",
    "fileprivate",
    "func",
    "import",
    "init",
    "inout",
    "internal",
    "let",
    "open",
    "operator",
    "private",
    "protocol",
    "public",
    "rethrows",
    "static",
    "struct",
    "subscript",
    "typealias",
    "var",
    "break",
    "case",
    "continue",
    "default",
    "defer",
    "do",
    "else",
    "fallthrough",
    "for",
    "guard",
    "if",
    "in",
    "repeat",
    "return",
    "switch",
    "where",
    "while",
    "as",
    "any",
    "catch",
    "false",
    "is",
    "nil",
    "self",
    "super",
    "throw",
    "throws",
    "true",
    "try",
];

/// Validate a Swift module name (SwiftPM `Package.swift` target/product `name:`). Swift
/// identifiers (Swift Language Reference, "Lexical Structure > Identifiers") start with one of
/// a specific list of Unicode scalar ranges (see
/// [`crate::codegen::identifier_grammar::is_swift_identifier_start`]) or `_`, and continue with
/// those plus digits and a narrower combining-mark range; unlike a JVM package or C# namespace,
/// a Swift module name has no internal dot-separated structure -- it is a single identifier,
/// since it becomes the argument to `import` and is embedded in mangled symbol names. SwiftPM
/// rejects a target name containing `.` or `-` for the same reason.
///
/// Two things `char::is_alphabetic()`/`is_alphanumeric()` get wrong here, both confirmed against
/// `swiftc` 6.3.1: they reject emoji such as U+1F600, which Swift's own grammar accepts as an
/// identifier character (`let 😀z = 1` compiles), and the reserved-word check below must compare
/// case-sensitively, since `Class` (capitalized) is an ordinary identifier while only the exact
/// spelling `class` is a keyword.
pub fn validate_swift_module_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("must not be empty".to_string());
    }
    let mut chars = name.chars();
    let first = chars.next().expect("name is non-empty");
    if !is_swift_identifier_start(first) {
        return Err(format!("`{name}` must start with a letter or `_`"));
    }
    if let Some(bad) = chars.find(|c| !is_swift_identifier_part(*c)) {
        return Err(format!(
            "`{name}` contains `{bad}`; a Swift module name has no internal `.`/`-` structure and must \
             be a single identifier"
        ));
    }
    if SWIFT_RESERVED.contains(&name) {
        return Err(format!(
            "`{name}` is a Swift reserved keyword and cannot be used unescaped"
        ));
    }
    Ok(())
}

/// Validate a SwiftPM package name (`Package(name: "...")`). Unlike [`validate_swift_module_name`]
/// (which governs the *module*/target/import identity and must be a single Swift identifier),
/// the package's own `name:` argument is a free-form manifest label with no identifier
/// grammar of its own -- real published packages routinely use kebab-case
/// (`swift-argument-parser`, `swift-collections`), which a strict identifier check would
/// wrongly reject. It is still a Swift string literal, so the only requirement is that it
/// cannot break out of the literal or trigger `\(...)` string interpolation (Swift Language
/// Reference, "String Literals"): reject a literal `"`, `\`, or control character.
pub fn validate_swift_package_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("must not be empty".to_string());
    }
    if let Some(bad) = name.chars().find(|c| *c == '"' || *c == '\\' || c.is_control()) {
        return Err(format!(
            "`{name}` contains `{bad}`, which would break out of the Swift string literal `Package(name: \"...\")` \
             is spliced into"
        ));
    }
    Ok(())
}

/// Dart reserved words (dart.dev/language/keywords, "Reserved words" -- words that can
/// never be used as identifiers, as opposed to the language's "built-in" and
/// contextual/limited-reserved keywords, which remain valid identifiers).
const DART_RESERVED: &[&str] = &[
    "assert", "break", "case", "catch", "class", "const", "continue", "default", "do", "else", "enum", "extends",
    "false", "final", "finally", "for", "if", "in", "is", "new", "null", "rethrow", "return", "super", "switch",
    "this", "throw", "true", "try", "var", "void", "while", "with",
];

/// Validate a Dart/pub.dev package name. pub.dev package-name conventions (dart.dev/tools/
/// pub/pubspec, "Package name conventions") require `lowercase_with_underscores`: ASCII
/// lowercase letters, digits, and `_` only, starting with a lowercase letter, and must
/// not be a Dart reserved word.
pub fn validate_dart_package_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("must not be empty".to_string());
    }
    let mut chars = name.chars();
    let first = chars.next().expect("name is non-empty");
    if !first.is_ascii_lowercase() {
        return Err(format!("`{name}` must start with a lowercase ASCII letter"));
    }
    if let Some(bad) = chars.find(|c| !(c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '_')) {
        return Err(format!(
            "`{name}` contains `{bad}`; pub.dev package names allow only lowercase ASCII letters, digits, and `_`"
        ));
    }
    if DART_RESERVED.contains(&name) {
        return Err(format!(
            "`{name}` is a Dart reserved word and cannot be used as a package name"
        ));
    }
    Ok(())
}

/// Validate a Dart library entrypoint basename (`[dart] lib_name`). This is spliced as a single
/// Dart import-URI path segment -- `import 'package:{pubspec_name}/{lib_name}.dart'` -- and as
/// the `lib/{lib_name}.dart` file on disk, never as a Dart source identifier.
///
/// This is deliberately looser than [`validate_dart_package_name`] (pub.dev's *package* name
/// convention, which really does require `lowercase_with_underscores` because pub.dev's own
/// validator enforces it): pub.dev does not require a library's file basename to be snake_case,
/// and `ResolvedCrateConfig::dart_bridge_class_name` already documents and normalizes a
/// hyphenated `lib_name` (e.g. `"sample-widget"` -> `"SampleWidgetBridge"`, via
/// `heck::ToUpperCamelCase`) as a supported, previously-working input shape -- applying the
/// stricter package-name grammar here would hard-reject a config that resolved cleanly before
/// coordinate validation existed. The only real hazards are the value escaping the single
/// import-URI path component it occupies, or breaking out of the Dart string literal it is
/// spliced into.
pub fn validate_dart_library_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("must not be empty".to_string());
    }
    if name.contains('/') || name.contains('\\') || name.contains("..") {
        return Err(format!(
            "`{name}` must be a single path component, with no `/`, `\\`, or `..`"
        ));
    }
    if name.ends_with(['.', ' ']) {
        return Err(format!("`{name}` must not end with a dot or space"));
    }
    let device_stem = name.split('.').next().unwrap_or(name);
    let uppercase_stem = device_stem.to_ascii_uppercase();
    let is_numbered_device = uppercase_stem
        .strip_prefix("COM")
        .or_else(|| uppercase_stem.strip_prefix("LPT"))
        .is_some_and(|suffix| {
            matches!(
                suffix,
                "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
            )
        });
    if matches!(uppercase_stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || is_numbered_device {
        return Err(format!("`{name}` uses a Windows-reserved file basename"));
    }
    if let Some(bad) = name
        .chars()
        .find(|c| matches!(*c, '\'' | '$' | '<' | '>' | ':' | '"' | '|' | '?' | '*') || c.is_control())
    {
        return Err(format!(
            "`{name}` contains `{bad}`, which is not valid in a portable file basename or the \
             Dart import string literal `import 'package:...'` it is spliced into"
        ));
    }
    Ok(())
}

/// Escape a string for interpolation into a Kotlin (Gradle KTS) double-quoted string
/// literal. Beyond `"` and `\`, Kotlin string literals have an ACTIVE construct: `$identifier`
/// and `${expression}` trigger string templates (Kotlin language specification, "String
/// templates"), so a literal `$` must become `\$` or injected config data can reference (or,
/// via `${...}`, evaluate) arbitrary in-scope Gradle build-script symbols. Grammar validation
/// (e.g. [`validate_java_package`]) already rejects most injection shapes for identifier-typed
/// coordinates, but `$` is a legal JVM identifier character, so this escape is the remaining
/// defense for any coordinate spliced into a raw `.kts` string literal.
pub fn kotlin_string_escape(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"").replace('$', "\\$")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn java_and_kotlin_packages_accept_typical_defaults() {
        for value in ["dev.sample_core", "com.github.foo_org", "unconfigured.alef"] {
            assert!(validate_java_package(value).is_ok());
            assert!(validate_kotlin_package(value).is_ok());
        }
    }

    #[test]
    fn jvm_package_accepts_unicode_letters() {
        assert!(
            validate_java_package("München.parser").is_ok(),
            "non-ASCII letters are legal Java identifiers"
        );
    }

    #[test]
    fn jvm_package_rejects_empty_and_double_dot_segments() {
        assert!(validate_java_package("").is_err());
        assert!(validate_java_package("dev..example").is_err());
        assert!(validate_java_package(".dev.example").is_err());
        assert!(validate_java_package("dev.example.").is_err());
    }

    #[test]
    fn jvm_package_rejects_path_traversal_segments() {
        assert!(validate_java_package("../../etc").is_err());
    }

    #[test]
    fn java_and_kotlin_package_grammars_are_distinct_and_case_sensitive() {
        assert!(validate_java_package("dev.class").is_err());
        assert!(validate_java_package("dev.Class").is_ok());
        assert!(validate_java_package("dev.fun").is_ok());
        assert!(validate_java_package("dev.$internal").is_ok());
        assert!(validate_kotlin_package("dev.class").is_err());
        assert!(validate_kotlin_package("dev.Class").is_ok());
        assert!(validate_kotlin_package("dev.fun").is_err());
        assert!(validate_kotlin_package("dev.$internal").is_err());
    }

    #[test]
    fn java_package_accepts_restricted_identifiers() {
        assert!(
            validate_java_package("dev.var").is_ok(),
            "var is a restricted identifier, not a keyword"
        );
        assert!(
            validate_java_package("dev.yield").is_ok(),
            "yield is a restricted identifier, not a keyword"
        );
        assert!(
            validate_java_package("dev.record").is_ok(),
            "record is a restricted identifier, not a keyword"
        );
    }

    #[test]
    fn jvm_package_rejects_injection_characters() {
        assert!(validate_java_package("dev\";System.exit(1);//").is_err());
        assert!(validate_kotlin_package("dev.example;import evil.Class").is_err());
    }

    #[test]
    fn maven_coordinate_accepts_hyphenated_group_ids() {
        assert!(validate_maven_coordinate("groupId", "io.projectreactor.netty").is_ok());
        assert!(validate_maven_coordinate("artifactId", "my-lib-android").is_ok());
    }

    #[test]
    fn maven_coordinate_rejects_empty_and_path_traversal() {
        assert!(validate_maven_coordinate("groupId", "").is_err());
        assert!(validate_maven_coordinate("groupId", "../../evil").is_err());
        assert!(validate_maven_coordinate("groupId", "dev/example").is_err());
        assert!(validate_maven_coordinate("groupId", ".dev").is_err());
        assert!(validate_maven_coordinate("groupId", "dev.").is_err());
    }

    #[test]
    fn maven_coordinate_rejects_quote_and_interpolation_characters() {
        assert!(validate_maven_coordinate("groupId", "dev\"); System.exit(1); //").is_err());
        assert!(validate_maven_coordinate("groupId", "dev${evil}").is_err());
    }

    #[test]
    fn nuget_package_id_accepts_typical_ids() {
        assert!(validate_nuget_package_id("MyCompany.MyLib").is_ok());
        assert!(validate_nuget_package_id("my_lib-android").is_ok());
    }

    #[test]
    fn nuget_package_id_matches_dotnet_word_character_categories() {
        assert!(validate_nuget_package_id("Cafe\u{301}").is_ok());
        assert!(validate_nuget_package_id("My\u{203f}Lib").is_ok());
        assert!(validate_nuget_package_id("München.Δοκιμή").is_ok());
        assert!(validate_nuget_package_id("").is_err());
        assert!(validate_nuget_package_id("²").is_err());
    }

    #[test]
    fn nuget_package_id_limit_counts_dotnet_utf16_code_units() {
        assert!(validate_nuget_package_id("𐐀").is_err());
        assert!(validate_nuget_package_id(&"𐐀".repeat(51)).is_err());
    }

    #[test]
    fn nuget_package_id_rejects_empty_leading_dot_and_quotes() {
        assert!(validate_nuget_package_id("").is_err());
        assert!(validate_nuget_package_id(".MyLib").is_err());
        assert!(validate_nuget_package_id("MyLib\"><Evil/>").is_err());
        assert!(validate_nuget_package_id("MyLib.").is_err());
        assert!(validate_nuget_package_id("MyLib-.Core").is_err());
        assert!(validate_nuget_package_id(&"a".repeat(101)).is_err());
        assert!(validate_nuget_package_id(&"a".repeat(100)).is_ok());
    }

    /// Ground-truth values taken directly from `icu_casemap::CaseMapperBorrowed::simple_fold`'s
    /// own doctest (icu_casemap 2.3.0), not re-derived here, so this proves `nuget_ordinal_fold`
    /// calls the function it claims to and doesn't silently no-op.
    #[test]
    fn nuget_ordinal_fold_matches_case_insensitively() {
        assert_eq!(nuget_ordinal_fold("MyLib"), nuget_ordinal_fold("mylib"));
        assert_eq!(nuget_ordinal_fold("MyLib"), nuget_ordinal_fold("MYLIB"));
        assert_ne!(nuget_ordinal_fold("MyLib"), nuget_ordinal_fold("MyLib2"));
        assert_ne!(nuget_ordinal_fold(""), nuget_ordinal_fold("ß"));
        assert_ne!(nuget_ordinal_fold("ſ"), nuget_ordinal_fold("S"));
        assert_ne!(nuget_ordinal_fold(""), nuget_ordinal_fold("K"));
    }

    #[test]
    fn nuget_ordinal_fold_does_not_expand_a_character_into_several() {
        // `simple_fold('ß') == 'ß'` (unchanged): full Unicode case folding would expand it to
        // "ss", which would silently change the collision key's length and diverge from .NET's
        // ordinal (one-code-unit-to-one-code-unit) comparer.
        assert_eq!(nuget_ordinal_fold("weiß"), "WEIß");
        assert_eq!(nuget_ordinal_fold("weiß").chars().count(), "weiß".chars().count());
    }

    #[test]
    fn dart_library_name_rejects_non_portable_file_basenames() {
        for name in [
            "CON", "com1", "Lpt9", "COM¹", "com²", "LPT³", "name:", "name*", "name?", "name\"", "name<", "name>",
            "name|",
        ] {
            assert!(validate_dart_library_name(name).is_err(), "accepted {name:?}");
        }
        assert!(validate_dart_library_name("trailing.").is_err());
        assert!(validate_dart_library_name("trailing ").is_err());
        assert!(validate_dart_library_name("sample-widget").is_ok());
    }

    #[test]
    fn csharp_namespace_accepts_unicode_letters() {
        assert!(validate_csharp_namespace("München.Parser").is_ok());
    }

    #[test]
    fn csharp_namespace_rejects_reserved_words_and_empty_segments() {
        assert!(validate_csharp_namespace("My.class").is_err());
        assert!(validate_csharp_namespace("My..Lib").is_err());
        assert!(validate_csharp_namespace("").is_err());
    }

    #[test]
    fn csharp_namespace_rejects_msbuild_and_quote_characters() {
        assert!(validate_csharp_namespace("My\"><Evil/>").is_err());
        assert!(validate_csharp_namespace("My.$(Evil)").is_err());
    }

    #[test]
    fn swift_module_name_accepts_typical_names() {
        assert!(validate_swift_module_name("SampleCore").is_ok());
        assert!(validate_swift_module_name("_SampleCore").is_ok());
    }

    #[test]
    fn swift_module_name_rejects_dots_dashes_and_reserved_words() {
        assert!(validate_swift_module_name("Sample.Core").is_err());
        assert!(validate_swift_module_name("sample-core").is_err());
        assert!(validate_swift_module_name("class").is_err());
        assert!(validate_swift_module_name("").is_err());
    }

    #[test]
    fn swift_module_name_rejects_interpolation_characters() {
        assert!(validate_swift_module_name("Sample\\(evilCode)").is_err());
    }

    #[test]
    fn swift_module_name_keyword_check_is_case_sensitive() {
        // Confirmed against swiftc 6.3.1: `struct Class { ... }` compiles, so a capitalized
        // spelling of a keyword is an ordinary identifier, not a reserved word.
        assert!(validate_swift_module_name("Class").is_ok());
        assert!(validate_swift_module_name("class").is_err());
    }

    #[test]
    fn swift_module_name_accepts_emoji() {
        // Confirmed against swiftc 6.3.1: `let 😀 = 1` and `let 🎉 = 1` both compile.
        assert!(validate_swift_module_name("\u{1F600}").is_ok());
        assert!(validate_swift_module_name("\u{1F389}").is_ok());
    }

    #[test]
    fn swift_package_name_accepts_kebab_case_and_dotted_names() {
        // Real published SwiftPM packages: apple/swift-argument-parser, apple/swift-collections.
        // `validate_swift_module_name`'s identifier grammar would wrongly reject these.
        assert!(validate_swift_package_name("swift-argument-parser").is_ok());
        assert!(validate_swift_package_name("Sample.Router").is_ok());
        assert!(validate_swift_package_name("Sample Router").is_ok());
    }

    #[test]
    fn swift_package_name_rejects_quote_and_backslash_but_not_dots() {
        assert!(validate_swift_package_name("Sample\"); print(\"evil").is_err());
        assert!(validate_swift_package_name("Sample\\(evilCode)").is_err());
        assert!(validate_swift_package_name("").is_err());
    }

    #[test]
    fn swift_package_name_rejects_control_characters() {
        for value in ["Sample\nInjected", "Sample\rInjected", "Sample\0Injected"] {
            assert!(
                validate_swift_package_name(value).is_err(),
                "`{value:?}` must be rejected"
            );
        }
    }

    #[test]
    fn dart_package_name_accepts_lowercase_with_underscores() {
        assert!(validate_dart_package_name("sample_core").is_ok());
    }

    #[test]
    fn dart_package_name_rejects_uppercase_dashes_and_reserved_words() {
        assert!(validate_dart_package_name("SampleCore").is_err());
        assert!(validate_dart_package_name("sample-core").is_err());
        assert!(validate_dart_package_name("var").is_err());
        assert!(validate_dart_package_name("").is_err());
    }

    #[test]
    fn dart_library_name_accepts_hyphens_that_the_package_name_grammar_rejects() {
        // `dart_bridge_class_name` documents and normalizes exactly this shape
        // (`"sample-widget"` -> `"SampleWidgetBridge"`); the library basename check must not
        // regress that into a hard resolve-time error.
        assert!(validate_dart_library_name("sample-widget").is_ok());
        assert!(validate_dart_package_name("sample-widget").is_err());
    }

    #[test]
    fn dart_library_name_rejects_path_traversal_and_string_breakout_characters() {
        assert!(validate_dart_library_name("").is_err());
        assert!(validate_dart_library_name("../evil").is_err());
        assert!(validate_dart_library_name("a/b").is_err());
        assert!(validate_dart_library_name("a\\b").is_err());
        assert!(validate_dart_library_name("evil'; import 'dart:io").is_err());
        assert!(validate_dart_library_name("evil${1+1}").is_err());
    }

    #[test]
    fn kotlin_string_escape_neutralizes_dollar_template_interpolation() {
        assert_eq!(kotlin_string_escape("dev.$evilVar"), "dev.\\$evilVar");
        assert_eq!(kotlin_string_escape("dev.${evil()}"), "dev.\\${evil()}");
    }

    #[test]
    fn kotlin_string_escape_neutralizes_quotes_and_backslashes() {
        assert_eq!(
            kotlin_string_escape("dev\"); System.exit(1); //"),
            "dev\\\"); System.exit(1); //"
        );
        assert_eq!(kotlin_string_escape("dev\\example"), "dev\\\\example");
    }

    #[test]
    fn kotlin_string_escape_is_identity_for_a_plain_valid_package() {
        let plain = "dev.sample_core";
        assert_eq!(kotlin_string_escape(plain), plain);
    }
}