lang-parsing-substrate 0.17.3

Shared language-parsing substrate for knots, moldy, aurora-lint, and clew
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! The language registry: `LANGUAGES`'s runtime form (`languages()`), and
//! every lookup consumers use to get from a file to a tree-sitter `Language`
//! — by file name or extension (`language_for_file`), by sniffed `.h` content
//! (`language_for_header_content`), or by registry key
//! (`language_for_key`). Also the extension-classification predicates
//! (`is_source_extension`, `is_parseable_extension`) that drive recursive
//! file discovery in knots and moldy, and `is_extension_for_language`, which
//! aurora-lint uses to discover C files only.
//!
//! # Extension case
//!
//! Every extension lookup here folds the path's extension to ASCII lowercase
//! first (`folded_extension`), so upper- and mixed-case extensions such as
//! `A.C`, `A.Cpp`, `MAIN.PY` and `lib.RS` resolve like their lowercase forms.
//! Source trees built on Windows, which has case-insensitive file names,
//! commonly arrive with uppercase extensions.
//!
//! `.C` is C and `.H` is a C header, because the uppercase files seen in
//! practice are Windows-built supplier trees. GCC's convention that `foo.C`
//! is C++ is deliberately not followed; a C++ project that names its sources
//! `.C` can parse them with `language_for_key("cpp")`. Fortran's `.F90`
//! (preprocessed by convention) and `.f90` share one grammar. Language keys and [`LanguageInfo::filenames`] are not folded: keys
//! are lowercase and matched exactly, and `CMakeLists.txt` is matched as
//! written.

use std::ffi::OsStr;
use std::path::Path;
use std::sync::OnceLock;
use tree_sitter::Language;

/// Which comment style a language uses (drives SLOC calculation).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SlocMode {
    /// `//` and `/* */` — C, C++, Rust, JS, TS, Go, Java, …
    Default,
    /// Additionally strips `#`-prefixed comment lines.
    Python,
    /// Strips `--` comment lines.
    Ada,
    /// Strips `--` comment lines (same prefix as Ada, distinct grammar).
    Lua,
    /// Strips `!` comment lines (free-form Fortran: `.f90`, `.f95`, …).
    Fortran,
    /// Strips `#` comment lines — YAML, CMake and Bash. Unlike [`SlocMode::Python`],
    /// it implies no `//` or `/* */` syntax.
    Hash,
    /// Strips single-line `<!-- … -->` HTML comments (Markdown).
    Markdown,
    /// Strips reStructuredText explicit-markup comment lines, which open with
    /// `..`. This is an approximation: `..` also opens directives, targets,
    /// substitutions and footnotes, so a line-based pass treats those as
    /// comments too. Good enough for the current consumers (RST is formatted
    /// by moldy, not SLOC-counted, and is not recursively discovered); revisit
    /// if a consumer needs to tell a true comment from a directive.
    Rst,
}

/// A language the substrate can parse, with its display name, file extensions
/// and names, and comment style.
#[derive(Debug, Clone, Copy)]
pub struct LanguageInfo {
    /// Human-facing name, e.g. "C++", "Ada".
    pub name: &'static str,
    /// Canonical machine key — matches the Cargo feature suffix and config-file
    /// section names (e.g. `[c.thresholds]` in knots.toml).
    /// Always lowercase ASCII; e.g. `"cpp"`, `"csharp"`, `"javascript"`.
    pub key: &'static str,
    /// Extensions used during recursive discovery (no leading dot), in
    /// lowercase. Lookups fold the path's extension to lowercase before
    /// comparing (see the module docs); Fortran also lists its uppercase
    /// forms for consumers that compare against this list directly.
    pub extensions: &'static [&'static str],
    /// Extensions parsed only when a file is passed explicitly — never
    /// discovered recursively (e.g. C's `.h` headers).
    pub explicit_only: &'static [&'static str],
    /// Exact file names that belong to this language whatever their
    /// extension, discovered recursively (e.g. CMake's `CMakeLists.txt`).
    /// Matched case-sensitively, and ahead of the extension.
    pub filenames: &'static [&'static str],
    /// Comment style for this language.
    pub sloc_mode: SlocMode,
}

/// Returns the set of languages compiled into this build.
///
/// The returned slice reflects only the languages enabled via Cargo features
/// at compile time. Iterate this to discover what the current binary supports
/// rather than hard-coding extension lists in each tool.
// vec![] can't express per-element #[cfg(...)] gates, so languages() below must
// stay Vec::new() + push despite clippy::vec_init_then_push.
#[allow(clippy::vec_init_then_push)]
pub fn languages() -> &'static [LanguageInfo] {
    static LANGS: OnceLock<Vec<LanguageInfo>> = OnceLock::new();
    LANGS.get_or_init(|| {
        #[allow(unused_mut)]
        let mut v: Vec<LanguageInfo> = Vec::new();

        #[cfg(feature = "lang-c")]
        v.push(LanguageInfo {
            name: "C",
            key: "c",
            extensions: &["c"],
            explicit_only: &["h"],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-cpp")]
        v.push(LanguageInfo {
            name: "C++",
            key: "cpp",
            extensions: &["cpp", "cc", "cxx", "hpp", "hxx"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-rust")]
        v.push(LanguageInfo {
            name: "Rust",
            key: "rust",
            extensions: &["rs"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-python")]
        v.push(LanguageInfo {
            name: "Python",
            key: "python",
            extensions: &["py"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Python,
        });

        #[cfg(feature = "lang-javascript")]
        v.push(LanguageInfo {
            name: "JavaScript",
            key: "javascript",
            extensions: &["js", "mjs", "cjs", "jsx"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-typescript")]
        v.push(LanguageInfo {
            name: "TypeScript",
            key: "typescript",
            extensions: &["ts", "tsx"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-ada")]
        v.push(LanguageInfo {
            name: "Ada",
            key: "ada",
            extensions: &["adb", "ada"],
            explicit_only: &["ads"],
            filenames: &[],
            sloc_mode: SlocMode::Ada,
        });

        #[cfg(feature = "lang-go")]
        v.push(LanguageInfo {
            name: "Go",
            key: "go",
            extensions: &["go"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-java")]
        v.push(LanguageInfo {
            name: "Java",
            key: "java",
            extensions: &["java"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-csharp")]
        v.push(LanguageInfo {
            name: "C#",
            key: "csharp",
            extensions: &["cs"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-kotlin")]
        v.push(LanguageInfo {
            name: "Kotlin",
            key: "kotlin",
            extensions: &["kt", "kts"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-swift")]
        v.push(LanguageInfo {
            name: "Swift",
            key: "swift",
            extensions: &["swift"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-php")]
        v.push(LanguageInfo {
            name: "PHP",
            key: "php",
            extensions: &["php"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-fortran")]
        v.push(LanguageInfo {
            name: "Fortran",
            key: "fortran",
            extensions: &["f90", "f95", "f03", "f08", "F90", "F95", "F03", "F08"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Fortran,
        });

        #[cfg(feature = "lang-scala")]
        v.push(LanguageInfo {
            name: "Scala",
            key: "scala",
            extensions: &["scala", "sc"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        #[cfg(feature = "lang-lua")]
        v.push(LanguageInfo {
            name: "Lua",
            key: "lua",
            extensions: &["lua"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Lua,
        });

        #[cfg(feature = "lang-yaml")]
        v.push(LanguageInfo {
            name: "YAML",
            key: "yaml",
            extensions: &["yaml", "yml"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Hash,
        });

        // `.jsonc` too: the grammar accepts `//` and `/* */` comments.
        #[cfg(feature = "lang-json")]
        v.push(LanguageInfo {
            name: "JSON",
            key: "json",
            extensions: &["json", "jsonc"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Default,
        });

        // The block grammar. Its `inline` nodes hold paragraph and heading
        // text unparsed; re-parse their ranges with the `markdown_inline`
        // grammar (`language_for_key`) for links, emphasis and code spans.
        #[cfg(feature = "lang-markdown")]
        v.push(LanguageInfo {
            name: "Markdown",
            key: "markdown",
            extensions: &["md", "markdown"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Markdown,
        });

        #[cfg(feature = "lang-cmake")]
        v.push(LanguageInfo {
            name: "CMake",
            key: "cmake",
            extensions: &["cmake"],
            explicit_only: &[],
            filenames: &["CMakeLists.txt"],
            sloc_mode: SlocMode::Hash,
        });

        // Extensionless scripts are found by `classify`'s shebang hint
        // (`sh`, `bash`, `dash`, `ksh`), not here.
        #[cfg(feature = "lang-bash")]
        v.push(LanguageInfo {
            name: "Bash",
            key: "bash",
            extensions: &["sh", "bash"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Hash,
        });

        // Documentation markup, like Markdown: grouped under `all-data-languages`
        // so knots doesn't discover `.rst` as source. moldy formats it.
        #[cfg(feature = "lang-rst")]
        v.push(LanguageInfo {
            name: "reStructuredText",
            key: "rst",
            extensions: &["rst"],
            explicit_only: &[],
            filenames: &[],
            sloc_mode: SlocMode::Rst,
        });

        v
    })
}

/// Returns the tree-sitter `Language` for `path` based on its file name
/// ([`LanguageInfo::filenames`]) or, failing that, its extension.
///
/// Returns `None` if the name and extension are unknown or if the
/// corresponding language feature was not compiled in.
pub fn language_for_file(path: &Path) -> Option<Language> {
    #[allow(clippy::match_single_binding)]
    match path.file_name().and_then(|n| n.to_str()) {
        #[cfg(feature = "lang-cmake")]
        Some("CMakeLists.txt") => return Some(tree_sitter_cmake::LANGUAGE.into()),

        _ => {}
    }

    match path_extension(path).as_deref() {
        #[cfg(feature = "lang-ada")]
        Some("adb" | "ada" | "ads") => Some(tree_sitter_ada::LANGUAGE.into()),

        #[cfg(feature = "lang-cpp")]
        Some("cpp" | "cc" | "cxx" | "hpp" | "hxx") => Some(tree_sitter_cpp::LANGUAGE.into()),

        #[cfg(feature = "lang-rust")]
        Some("rs") => Some(tree_sitter_rust::LANGUAGE.into()),

        #[cfg(feature = "lang-python")]
        Some("py") => Some(tree_sitter_python::LANGUAGE.into()),

        #[cfg(feature = "lang-javascript")]
        Some("js" | "mjs" | "cjs" | "jsx") => Some(tree_sitter_javascript::LANGUAGE.into()),

        #[cfg(feature = "lang-typescript")]
        Some("ts") => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),

        #[cfg(feature = "lang-typescript")]
        Some("tsx") => Some(tree_sitter_typescript::LANGUAGE_TSX.into()),

        #[cfg(feature = "lang-go")]
        Some("go") => Some(tree_sitter_go::LANGUAGE.into()),

        #[cfg(feature = "lang-java")]
        Some("java") => Some(tree_sitter_java::LANGUAGE.into()),

        #[cfg(feature = "lang-csharp")]
        Some("cs") => Some(tree_sitter_c_sharp::LANGUAGE.into()),

        #[cfg(feature = "lang-kotlin")]
        Some("kt" | "kts") => Some(tree_sitter_kotlin_ng::LANGUAGE.into()),

        #[cfg(feature = "lang-swift")]
        Some("swift") => Some(tree_sitter_swift::LANGUAGE.into()),

        #[cfg(feature = "lang-php")]
        Some("php") => Some(tree_sitter_php::LANGUAGE_PHP.into()),

        #[cfg(feature = "lang-fortran")]
        Some("f90" | "f95" | "f03" | "f08") => Some(tree_sitter_fortran::LANGUAGE.into()),

        #[cfg(feature = "lang-scala")]
        Some("scala" | "sc") => Some(tree_sitter_scala::LANGUAGE.into()),

        #[cfg(feature = "lang-lua")]
        Some("lua") => Some(tree_sitter_lua::LANGUAGE.into()),

        #[cfg(feature = "lang-yaml")]
        Some("yaml" | "yml") => Some(tree_sitter_yaml::LANGUAGE.into()),

        #[cfg(feature = "lang-json")]
        Some("json" | "jsonc") => Some(tree_sitter_json::LANGUAGE.into()),

        #[cfg(feature = "lang-markdown")]
        Some("md" | "markdown") => Some(tree_sitter_md::LANGUAGE.into()),

        #[cfg(feature = "lang-cmake")]
        Some("cmake") => Some(tree_sitter_cmake::LANGUAGE.into()),

        #[cfg(feature = "lang-bash")]
        Some("sh" | "bash") => Some(tree_sitter_bash::LANGUAGE.into()),

        #[cfg(feature = "lang-rst")]
        Some("rst") => Some(tree_sitter_rst::LANGUAGE.into()),

        #[cfg(feature = "lang-c")]
        Some("c" | "h") => Some(tree_sitter_c::LANGUAGE.into()),

        _ => None,
    }
}

/// Best-effort content-aware variant of [`language_for_file`] for callers
/// that already have the file's bytes in hand (e.g. because they're about
/// to parse it anyway). Identical to [`language_for_file`] for every
/// extension except `.h`: a `.h` file is ambiguous between C and C++, and
/// this checks `source` for an unambiguous C++-only construct
/// ([`crate::sniff_header`]) before falling back to `language_for_file`'s
/// default of C. See that function's module docs for what counts as
/// unambiguous and why a "no" doesn't mean "confirmed C".
///
/// The check runs within [`crate::ParseBudget::default`]. A header whose
/// parse reaches it is undecided, and gets the default of C here, since this
/// function overrides the extension only on evidence. A caller that must
/// report such a file calls [`crate::sniff_header`] itself. Parsing such a
/// header with the C grammar is just as slow as the sniff would have been,
/// so parse it with [`crate::parse_within_budget`] too.
#[cfg(all(feature = "lang-c", feature = "lang-cpp"))]
pub fn language_for_header_content(path: &Path, source: &[u8]) -> Option<Language> {
    match path_extension(path).as_deref() {
        Some("h") if crate::cpp_header::sniff_header(source) == crate::HeaderSniff::Cpp => {
            Some(tree_sitter_cpp::LANGUAGE.into())
        }
        _ => language_for_file(path),
    }
}

/// Returns the tree-sitter `Language` for the given canonical language key.
///
/// The key is the [`LanguageInfo::key`] value defined by this registry — e.g.
/// `"c"`, `"cpp"`, `"rust"`. Returns `None` if the key is unknown or the
/// corresponding language feature was not compiled in.
///
/// This is the complement to [`language_for_file`]: use it when you already
/// have a key (from [`LanguageInfo::key`]) and want the grammar without
/// constructing a fake file path.
///
/// Two keys name a grammar that has no [`LanguageInfo`] of its own: `"tsx"`
/// (filed under `typescript`) and `"markdown_inline"`, the second-pass
/// grammar for the text inside Markdown's `inline` nodes (filed under
/// `markdown`).
pub fn language_for_key(key: &str) -> Option<Language> {
    match key {
        #[cfg(feature = "lang-ada")]
        "ada" => Some(tree_sitter_ada::LANGUAGE.into()),

        #[cfg(feature = "lang-bash")]
        "bash" => Some(tree_sitter_bash::LANGUAGE.into()),

        #[cfg(feature = "lang-c")]
        "c" => Some(tree_sitter_c::LANGUAGE.into()),

        #[cfg(feature = "lang-cmake")]
        "cmake" => Some(tree_sitter_cmake::LANGUAGE.into()),

        #[cfg(feature = "lang-cpp")]
        "cpp" => Some(tree_sitter_cpp::LANGUAGE.into()),

        #[cfg(feature = "lang-csharp")]
        "csharp" => Some(tree_sitter_c_sharp::LANGUAGE.into()),

        #[cfg(feature = "lang-fortran")]
        "fortran" => Some(tree_sitter_fortran::LANGUAGE.into()),

        #[cfg(feature = "lang-go")]
        "go" => Some(tree_sitter_go::LANGUAGE.into()),

        #[cfg(feature = "lang-java")]
        "java" => Some(tree_sitter_java::LANGUAGE.into()),

        #[cfg(feature = "lang-javascript")]
        "javascript" => Some(tree_sitter_javascript::LANGUAGE.into()),

        #[cfg(feature = "lang-json")]
        "json" => Some(tree_sitter_json::LANGUAGE.into()),

        #[cfg(feature = "lang-kotlin")]
        "kotlin" => Some(tree_sitter_kotlin_ng::LANGUAGE.into()),

        #[cfg(feature = "lang-lua")]
        "lua" => Some(tree_sitter_lua::LANGUAGE.into()),

        #[cfg(feature = "lang-markdown")]
        "markdown" => Some(tree_sitter_md::LANGUAGE.into()),

        #[cfg(feature = "lang-markdown")]
        "markdown_inline" => Some(tree_sitter_md::INLINE_LANGUAGE.into()),

        #[cfg(feature = "lang-php")]
        "php" => Some(tree_sitter_php::LANGUAGE_PHP.into()),

        #[cfg(feature = "lang-python")]
        "python" => Some(tree_sitter_python::LANGUAGE.into()),

        #[cfg(feature = "lang-rst")]
        "rst" => Some(tree_sitter_rst::LANGUAGE.into()),

        #[cfg(feature = "lang-rust")]
        "rust" => Some(tree_sitter_rust::LANGUAGE.into()),

        #[cfg(feature = "lang-scala")]
        "scala" => Some(tree_sitter_scala::LANGUAGE.into()),

        #[cfg(feature = "lang-swift")]
        "swift" => Some(tree_sitter_swift::LANGUAGE.into()),

        #[cfg(feature = "lang-typescript")]
        "typescript" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),

        #[cfg(feature = "lang-typescript")]
        "tsx" => Some(tree_sitter_typescript::LANGUAGE_TSX.into()),

        #[cfg(feature = "lang-yaml")]
        "yaml" => Some(tree_sitter_yaml::LANGUAGE.into()),

        _ => None,
    }
}

/// Returns the [`LanguageInfo`] for `path` based on its file name or, failing
/// that, its extension — the same order as [`language_for_file`].
///
/// Unlike [`language_for_file`], this does not require a tree-sitter grammar —
/// it is suitable for tools (e.g. formatters) that dispatch per-language
/// without parsing. Returns `None` if the name and extension are unknown or
/// the corresponding language feature was not compiled in.
pub fn language_info_for_file(path: &Path) -> Option<&'static LanguageInfo> {
    if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
        if let Some(info) = languages().iter().find(|l| l.filenames.contains(&name)) {
            return Some(info);
        }
    }
    let ext = path_extension(path)?;
    languages().iter().find(|l| has_extension(l, &ext))
}

/// `ext` folded to ASCII lowercase, the form every extension lookup compares
/// (see the module docs). `None` if `ext` is not UTF-8.
fn folded_extension(ext: &OsStr) -> Option<String> {
    ext.to_str().map(str::to_ascii_lowercase)
}

/// The extension of `path`, folded by [`folded_extension`].
fn path_extension(path: &Path) -> Option<String> {
    path.extension().and_then(folded_extension)
}

/// Whether the folded extension `ext` is one of `lang`'s recursive-discovery
/// or explicit-only extensions.
fn has_extension(lang: &LanguageInfo, ext: &str) -> bool {
    lang.extensions.contains(&ext) || lang.explicit_only.contains(&ext)
}

/// Returns the [`SlocMode`] for `path`.
///
/// Returns `None` if the extension is unknown or the corresponding language
/// feature was not compiled in. Consumers that want a fallback should use
/// `sloc_mode_for_file(path).unwrap_or(SlocMode::Default)`.
pub fn sloc_mode_for_file(path: &Path) -> Option<SlocMode> {
    language_info_for_file(path).map(|l| l.sloc_mode)
}

/// Returns `true` if a recursive walk should pick up `path`: its file name is
/// in some compiled-in language's [`LanguageInfo::filenames`] (e.g.
/// `CMakeLists.txt`), or its extension is a recursive-discovery extension
/// ([`is_source_extension`]). Explicit-only extensions (C's `.h`) are not
/// discoverable. Looks at the path only; extensionless scripts need
/// [`crate::classify()`]'s shebang hint.
pub fn is_discoverable_file(path: &Path) -> bool {
    let named = path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| languages().iter().any(|l| l.filenames.contains(&n)));
    named || path.extension().is_some_and(is_source_extension)
}

/// Returns `true` if `ext` is in the recursive-discovery set for any
/// compiled-in language. Looks at extensions only: a discovery walk that
/// should also find [`LanguageInfo::filenames`] (e.g. `CMakeLists.txt`) calls
/// [`is_discoverable_file`] instead.
pub fn is_source_extension(ext: &OsStr) -> bool {
    folded_extension(ext).is_some_and(|e| {
        languages()
            .iter()
            .any(|l| l.extensions.contains(&e.as_str()))
    })
}

/// Returns `true` if the substrate can parse files with `ext` — includes both
/// recursive-discovery extensions and explicit-only ones (e.g. headers),
/// across *every* compiled-in language.
///
/// A consumer that only ever wants to discover files for one specific
/// language (or a fixed set), and enables other `lang-*` features purely for
/// narrow non-discovery use (e.g. [`crate::looks_like_cpp`]), should use
/// [`is_extension_for_language`] instead — this function's result changes
/// whenever the enabled feature set changes, which is rarely what a
/// single-language consumer wants.
pub fn is_parseable_extension(ext: &OsStr) -> bool {
    folded_extension(ext).is_some_and(|e| languages().iter().any(|l| has_extension(l, &e)))
}

/// Returns `true` if `ext` is a recursive-discovery or explicit-only
/// extension for the language keyed `key` specifically — unaffected by
/// whatever *other* languages happen to be compiled in.
///
/// `is_parseable_extension`/`is_source_extension` check membership against
/// the union of every compiled-in language, which silently widens for a
/// consumer that enables a second `lang-*` feature for a narrow,
/// non-discovery purpose (e.g. a disambiguation helper like
/// [`crate::looks_like_cpp`]). A consumer doing single- or fixed-language
/// file discovery should use this instead, checking against its own known
/// key(s), so enabling another language's feature can never change what
/// counts as "my source files". Returns `false` if `key` is unknown or its
/// feature was not compiled in.
pub fn is_extension_for_language(ext: &OsStr, key: &str) -> bool {
    folded_extension(ext).is_some_and(|e| {
        languages()
            .iter()
            .find(|l| l.key == key)
            .is_some_and(|l| has_extension(l, &e))
    })
}

/// Renders a human-readable summary of compiled-in languages, suitable for
/// a `--supported-languages` flag.
pub fn supported_languages_report() -> String {
    let langs = languages();
    let width = langs.iter().map(|l| l.name.len()).max().unwrap_or(0);
    let mut out = String::from("Supported languages:\n");
    for lang in langs {
        let exts = lang
            .filenames
            .iter()
            .map(|n| n.to_string())
            .chain(lang.extensions.iter().map(|e| format!(".{e}")))
            .collect::<Vec<_>>()
            .join(" ");
        out.push_str(&format!("  {:<width$}  {exts}", lang.name, width = width));
        if !lang.explicit_only.is_empty() {
            let extra = lang
                .explicit_only
                .iter()
                .map(|e| format!(".{e}"))
                .collect::<Vec<_>>()
                .join(" ");
            out.push_str(&format!("  (also {extra} when passed explicitly)"));
        }
        out.push('\n');
    }
    out
}

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

    /// Every registered extension (recursive and explicit-only) must map to a
    /// grammar via `language_for_file`, and only C extensions may map to the C
    /// grammar. Guards against an extension silently failing to dispatch.
    #[cfg(feature = "lang-c")]
    #[test]
    fn every_registered_extension_maps_to_its_grammar() {
        let c_lang: Language = tree_sitter_c::LANGUAGE.into();
        for lang in languages() {
            for ext in lang.extensions.iter().chain(lang.explicit_only) {
                let mapped = language_for_file(Path::new(&format!("f.{ext}")))
                    .unwrap_or_else(|| panic!(".{ext} ({}) did not map to a grammar", lang.name));
                if lang.key != "c" {
                    assert_ne!(
                        mapped, c_lang,
                        ".{ext} ({}) fell through to the C grammar",
                        lang.name
                    );
                }
            }
        }
    }

    #[test]
    fn unknown_extension_has_no_language() {
        assert!(language_for_file(Path::new("notes.txt")).is_none());
        assert!(sloc_mode_for_file(Path::new("notes.txt")).is_none());
        assert!(language_for_file(Path::new("noext")).is_none());
    }

    #[cfg(feature = "lang-fortran")]
    #[test]
    fn fortran_sloc_mode() {
        for ext in ["f90", "f95", "F90"] {
            assert_eq!(
                sloc_mode_for_file(Path::new(&format!("modern.{ext}"))),
                Some(SlocMode::Fortran),
                ".{ext} should be free-form Fortran",
            );
        }
    }

    /// A file name match wins over the extension, and only the exact name
    /// matches: other `.txt` files stay unknown.
    #[cfg(feature = "lang-cmake")]
    #[test]
    fn cmakelists_resolves_by_file_name() {
        let cmake: Language = tree_sitter_cmake::LANGUAGE.into();
        for path in ["CMakeLists.txt", "src/sub/CMakeLists.txt", "util.cmake"] {
            assert_eq!(
                language_for_file(Path::new(path)),
                Some(cmake.clone()),
                "{path}"
            );
            assert_eq!(
                language_info_for_file(Path::new(path)).map(|l| l.key),
                Some("cmake"),
                "{path}"
            );
        }
        for path in ["cmakelists.txt", "CMakeLists.txt.bak", "notes.txt"] {
            assert!(language_for_file(Path::new(path)).is_none(), "{path}");
            assert!(language_info_for_file(Path::new(path)).is_none(), "{path}");
        }
        assert!(supported_languages_report().contains("CMakeLists.txt .cmake"));
    }

    /// `is_discoverable_file` takes registered file names and discovery
    /// extensions, and nothing explicit-only.
    #[test]
    fn is_discoverable_file_covers_names_and_discovery_extensions() {
        for lang in languages() {
            for name in lang.filenames {
                assert!(is_discoverable_file(Path::new(name)), "{name}");
            }
            for ext in lang.extensions {
                assert!(
                    is_discoverable_file(Path::new(&format!("d/f.{ext}"))),
                    ".{ext}"
                );
            }
            for ext in lang.explicit_only {
                assert!(
                    !is_discoverable_file(Path::new(&format!("f.{ext}"))),
                    ".{ext}"
                );
            }
        }
        assert!(!is_discoverable_file(Path::new("notes.txt")));
        assert!(!is_discoverable_file(Path::new("noext")));
    }

    /// Every registered file name must resolve to its own language through
    /// both lookups.
    #[test]
    fn every_registered_filename_maps_to_its_language() {
        for lang in languages() {
            for name in lang.filenames {
                let path = Path::new(name);
                assert_eq!(
                    language_info_for_file(path).map(|l| l.key),
                    Some(lang.key),
                    "{name}"
                );
                assert_eq!(
                    language_for_file(path),
                    language_for_key(lang.key),
                    "{name} disagrees with language_for_key({:?})",
                    lang.key
                );
            }
        }
    }

    #[cfg(feature = "lang-markdown")]
    #[test]
    fn markdown_inline_is_a_grammar_key_only() {
        let inline: Language = tree_sitter_md::INLINE_LANGUAGE.into();
        assert_eq!(language_for_key("markdown_inline"), Some(inline.clone()));
        assert_ne!(language_for_key("markdown"), Some(inline));
        assert!(languages().iter().all(|l| l.key != "markdown_inline"));
    }

    #[cfg(feature = "lang-python")]
    #[test]
    fn python_sloc_mode() {
        assert_eq!(
            sloc_mode_for_file(Path::new("a.py")),
            Some(SlocMode::Python)
        );
    }

    /// Every `LanguageInfo.key` must be lowercase ASCII and unique — consumers
    /// use it as a config-section name (e.g. `[funky.cpp]`) and would silently
    /// collide on duplicates or mismatched case.
    #[test]
    fn keys_are_lowercase_and_unique() {
        let mut seen = std::collections::HashSet::new();
        for lang in languages() {
            assert!(
                lang.key.chars().all(|c| c.is_ascii_lowercase()),
                "{} key {:?} is not lowercase ASCII",
                lang.name,
                lang.key
            );
            assert!(
                seen.insert(lang.key),
                "duplicate LanguageInfo.key {:?}",
                lang.key
            );
        }
    }

    /// `language_info_for_file` must agree with `language_for_file` on every
    /// registered extension — same set of extensions resolve in both, with no
    /// grammar requirement.
    #[test]
    fn language_info_for_file_matches_extensions() {
        for lang in languages() {
            for ext in lang.extensions.iter().chain(lang.explicit_only) {
                let info =
                    language_info_for_file(Path::new(&format!("f.{ext}"))).unwrap_or_else(|| {
                        panic!(".{ext} ({}) did not resolve to a LanguageInfo", lang.name)
                    });
                assert_eq!(
                    info.key, lang.key,
                    ".{ext} resolved to the wrong LanguageInfo"
                );
            }
        }
        assert!(language_info_for_file(Path::new("notes.txt")).is_none());
        assert!(language_info_for_file(Path::new("noext")).is_none());
    }

    /// `is_source_extension` covers only recursive-discovery extensions;
    /// `is_parseable_extension` additionally covers explicit-only ones
    /// (headers, etc). An explicit-only extension must never be reported as a
    /// source (discoverable) extension.
    #[test]
    fn source_vs_parseable_extension_distinction() {
        for lang in languages() {
            for ext in lang.extensions {
                let os_ext = std::ffi::OsStr::new(ext);
                assert!(
                    is_source_extension(os_ext),
                    ".{ext} ({}) should be a source extension",
                    lang.name
                );
                assert!(
                    is_parseable_extension(os_ext),
                    ".{ext} ({}) should be parseable",
                    lang.name
                );
            }
            for ext in lang.explicit_only {
                let os_ext = std::ffi::OsStr::new(ext);
                assert!(
                    !is_source_extension(os_ext),
                    ".{ext} ({}) is explicit-only and must not be a source extension",
                    lang.name
                );
                assert!(
                    is_parseable_extension(os_ext),
                    ".{ext} ({}) should still be parseable",
                    lang.name
                );
            }
        }
        assert!(!is_source_extension(std::ffi::OsStr::new("txt")));
        assert!(!is_parseable_extension(std::ffi::OsStr::new("txt")));
    }

    /// `is_extension_for_language` must only report `true` for the given
    /// language's own extensions, regardless of what else is compiled in —
    /// this is the guard against the footgun `is_parseable_extension`
    /// widening file discovery when an unrelated `lang-*` feature is enabled
    /// for a narrow, non-discovery purpose.
    #[test]
    fn is_extension_for_language_is_scoped_to_one_language() {
        for lang in languages() {
            for ext in lang.extensions.iter().chain(lang.explicit_only) {
                let os_ext = std::ffi::OsStr::new(ext);
                assert!(
                    is_extension_for_language(os_ext, lang.key),
                    ".{ext} should be an extension of {}",
                    lang.key
                );
                for other in languages().iter().filter(|l| l.key != lang.key) {
                    assert!(
                        !is_extension_for_language(os_ext, other.key),
                        ".{ext} (belongs to {}) must not be reported as an extension of {}",
                        lang.key,
                        other.key
                    );
                }
            }
        }
        assert!(!is_extension_for_language(std::ffi::OsStr::new("txt"), "c"));
        assert!(!is_extension_for_language(
            std::ffi::OsStr::new("c"),
            "not-a-real-key"
        ));
    }

    /// `language_for_key` must round-trip with `LanguageInfo.key` for every
    /// compiled-in language: `language_for_key(info.key)` must return the same
    /// `Language` as `language_for_file` on a file with one of that language's
    /// registered extensions.
    #[test]
    fn language_for_key_round_trips_with_language_info() {
        for lang in languages() {
            let by_key = language_for_key(lang.key).unwrap_or_else(|| {
                panic!(
                    "language_for_key({:?}) returned None for compiled-in language {}",
                    lang.key, lang.name
                )
            });
            // Pick any registered extension to get the canonical Language via
            // the file-based path and verify both routes agree.
            let ext = lang
                .extensions
                .first()
                .or_else(|| lang.explicit_only.first())
                .unwrap();
            let by_file = language_for_file(Path::new(&format!("f.{ext}"))).unwrap_or_else(|| {
                panic!(
                    ".{ext} ({}) did not resolve via language_for_file",
                    lang.name
                )
            });
            assert_eq!(
                by_key, by_file,
                "language_for_key({:?}) disagrees with language_for_file for {}",
                lang.key, lang.name
            );
        }
    }

    /// Keys not in the registry return None.
    #[test]
    fn language_for_key_unknown_returns_none() {
        assert!(language_for_key("").is_none());
        assert!(language_for_key("txt").is_none());
        assert!(language_for_key("C").is_none()); // case-sensitive
    }

    /// The report must mention every compiled-in language's name and every one
    /// of its recursive-discovery extensions, with explicit-only extensions
    /// called out separately.
    #[test]
    fn supported_languages_report_lists_every_language() {
        let report = supported_languages_report();
        for lang in languages() {
            assert!(
                report.contains(lang.name),
                "report missing language {}",
                lang.name
            );
            for ext in lang.extensions {
                assert!(
                    report.contains(&format!(".{ext}")),
                    "report missing extension .{ext} for {}",
                    lang.name
                );
            }
        }
    }

    /// Extensions match whatever their case: an upper- or mixed-case form
    /// resolves exactly as the lowercase one does, in every lookup.
    #[test]
    fn extension_lookups_fold_case() {
        for lang in languages() {
            for ext in lang.extensions.iter().chain(lang.explicit_only) {
                let lower = ext.to_ascii_lowercase();
                let mut mixed: Vec<char> = lower.chars().collect();
                mixed[0] = mixed[0].to_ascii_uppercase();
                let mixed: String = mixed.into_iter().collect();
                for variant in [ext.to_ascii_uppercase(), mixed] {
                    let path = format!("f.{variant}");
                    let os_ext = std::ffi::OsStr::new(&variant);
                    assert_eq!(
                        language_for_file(Path::new(&path)),
                        language_for_file(Path::new(&format!("f.{lower}"))),
                        "{path} ({})",
                        lang.name
                    );
                    assert_eq!(
                        language_info_for_file(Path::new(&path)).map(|l| l.key),
                        Some(lang.key),
                        "{path}"
                    );
                    assert!(is_extension_for_language(os_ext, lang.key), "{path}");
                    assert!(is_parseable_extension(os_ext), "{path}");
                    let discoverable = lang.extensions.contains(ext);
                    assert_eq!(is_source_extension(os_ext), discoverable, "{path}");
                    assert_eq!(
                        is_discoverable_file(Path::new(&path)),
                        discoverable,
                        "{path}"
                    );
                }
            }
        }
    }

    /// `.C` and `.H` are C, not C++: uppercase extensions come from
    /// Windows-built C trees, so GCC's `foo.C`-is-C++ convention is not
    /// followed. `.Cpp` and `.HPP` stay C++.
    #[cfg(all(feature = "lang-c", feature = "lang-cpp"))]
    #[test]
    fn uppercase_c_is_c_and_mixed_case_cpp_is_cpp() {
        let c: Language = tree_sitter_c::LANGUAGE.into();
        let cpp: Language = tree_sitter_cpp::LANGUAGE.into();
        let os = std::ffi::OsStr::new;
        for name in ["A.C", "B.H", "src/x.C", "x.h"] {
            assert_eq!(
                language_for_file(Path::new(name)),
                Some(c.clone()),
                "{name}"
            );
            assert_eq!(
                language_info_for_file(Path::new(name)).map(|l| l.key),
                Some("c"),
                "{name}"
            );
        }
        for name in ["a.Cpp", "a.CPP", "b.HPP", "c.Cc", "d.CXX"] {
            assert_eq!(
                language_for_file(Path::new(name)),
                Some(cpp.clone()),
                "{name}"
            );
        }
        assert!(is_extension_for_language(os("C"), "c"));
        assert!(is_extension_for_language(os("H"), "c"));
        assert!(!is_extension_for_language(os("C"), "cpp"));
        assert!(is_extension_for_language(os("Cpp"), "cpp"));
        assert!(!is_extension_for_language(os("Cpp"), "c"));
        assert!(is_source_extension(os("C")));
        assert!(!is_source_extension(os("H")), ".H stays explicit-only");
        assert!(is_parseable_extension(os("H")));
        assert!(is_discoverable_file(Path::new("up/A.C")));
        assert!(!is_discoverable_file(Path::new("up/B.H")));
        // Content sniffing still applies to an uppercase header.
        assert_eq!(
            language_for_header_content(Path::new("B.H"), b"#define X 1\n"),
            Some(c)
        );
        assert_eq!(
            language_for_header_content(Path::new("B.H"), b"namespace n { }\n"),
            Some(cpp)
        );
    }
}