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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! PyO3 bindings, feature-gated behind `pyo3`. Every public function here
//! owns its parse: Python cannot hand in a `tree_sitter::Node`/`Tree` (this
//! crate's `tree-sitter` version has no ABI relationship to tree-sitter's own
//! separate Python bindings), so each wrapper takes `(language_key, source)`,
//! parses internally, walks the tree, and returns only owned data.
//!
//! Consumers that need the tree itself for their own semantic walks (e.g.
//! clew's thread/lock harvesting) call `parse_tree`, which returns every node
//! as flat columns ([`crate::flat`]) they can wrap in their own node type. The
//! rest of this module exposes the substrate's analysis primitives.
//!
//! `useless_conversion` is allowed crate-wide-in-this-module: pyo3 0.22's
//! `#[pyfunction]` expansion applies a `?`/`From<PyErr>` conversion clippy
//! flags as a no-op on functions that already return `PyResult` — a
//! macro-generated false positive, not something callable here can fix.
#![allow(clippy::useless_conversion)]

use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyString};
use std::sync::atomic::{AtomicU64, Ordering};
use tree_sitter::Parser;

use crate::calls;
use crate::calls::CallEdge;
use crate::cfg;
use crate::cfg::{BasicBlock, CfgEdge, FunctionCfg};
use crate::classify::{self as classify_mod, BinaryKind, ClassifyLimits, FileClass, TextEncoding};
use crate::fingerprint;
use crate::fingerprint::Fingerprint;
use crate::flat::{self, FlatTree};
use crate::imports;
#[cfg(feature = "lang-markdown")]
use crate::markdown::{self, FrontMatter, FrontMatterKind, Section};
use crate::path_ignore;
use crate::regions;
use crate::regions::IgnoredRegion;
use crate::registry;
use crate::registry::LanguageInfo;
use crate::suppressions as suppressions_mod;
use crate::suppressions::Suppression;
use crate::tsquery::{self, Capture};

fn parse(language_key: &str, source: &[u8]) -> PyResult<tree_sitter::Tree> {
    let language = registry::language_for_key(language_key)
        .ok_or_else(|| PyValueError::new_err(format!("unknown language key: {language_key}")))?;
    let mut parser = Parser::new();
    parser
        .set_language(&language)
        .map_err(|e| PyValueError::new_err(e.to_string()))?;
    parser
        .parse(source, None)
        .ok_or_else(|| PyValueError::new_err("tree-sitter failed to parse source"))
}

fn sloc_mode_for_key(language_key: &str) -> PyResult<registry::SlocMode> {
    // `tsx` and `markdown_inline` are grammar keys (`language_for_key`) but not
    // `LanguageInfo` keys: the registry files them under `typescript` and
    // `markdown`, whose comment syntax they share.
    let info_key = match language_key {
        "tsx" => "typescript",
        "markdown_inline" => "markdown",
        _ => language_key,
    };
    registry::languages()
        .iter()
        .find(|l| l.key == info_key)
        .map(|l| l.sloc_mode)
        .ok_or_else(|| PyValueError::new_err(format!("unknown language key: {language_key}")))
}

#[pyclass(name = "LanguageInfo")]
#[derive(Clone)]
struct PyLanguageInfo {
    #[pyo3(get)]
    name: String,
    #[pyo3(get)]
    key: String,
    #[pyo3(get)]
    extensions: Vec<String>,
    #[pyo3(get)]
    explicit_only: Vec<String>,
    #[pyo3(get)]
    filenames: Vec<String>,
}

impl From<&LanguageInfo> for PyLanguageInfo {
    fn from(info: &LanguageInfo) -> Self {
        Self {
            name: info.name.to_string(),
            key: info.key.to_string(),
            extensions: info.extensions.iter().map(|s| s.to_string()).collect(),
            explicit_only: info.explicit_only.iter().map(|s| s.to_string()).collect(),
            filenames: info.filenames.iter().map(|s| s.to_string()).collect(),
        }
    }
}

#[pyclass(name = "CallEdge")]
#[derive(Clone)]
struct PyCallEdge {
    #[pyo3(get)]
    caller: String,
    #[pyo3(get)]
    callee: String,
    #[pyo3(get)]
    is_external: bool,
}

impl From<CallEdge> for PyCallEdge {
    fn from(e: CallEdge) -> Self {
        Self {
            caller: e.caller,
            callee: e.callee,
            is_external: e.is_external,
        }
    }
}

#[pyclass(name = "BasicBlock")]
#[derive(Clone)]
struct PyBasicBlock {
    #[pyo3(get)]
    id: usize,
    #[pyo3(get)]
    statements: Vec<(usize, usize)>,
    #[pyo3(get)]
    byte_range: (usize, usize),
    #[pyo3(get)]
    condition_range: Option<(usize, usize)>,
}

impl From<&BasicBlock> for PyBasicBlock {
    fn from(b: &BasicBlock) -> Self {
        Self {
            id: b.id,
            statements: b.statements.clone(),
            byte_range: b.byte_range,
            condition_range: b.condition_range,
        }
    }
}

fn cfg_edge_name(edge: CfgEdge) -> &'static str {
    match edge {
        CfgEdge::Fallthrough => "fallthrough",
        CfgEdge::TrueBranch => "true_branch",
        CfgEdge::FalseBranch => "false_branch",
        CfgEdge::BackEdge => "back_edge",
        CfgEdge::Return => "return",
        CfgEdge::Break => "break",
        CfgEdge::Continue => "continue",
    }
}

#[pyclass(name = "FunctionCfg")]
#[derive(Clone)]
struct PyFunctionCfg {
    #[pyo3(get)]
    blocks: Vec<PyBasicBlock>,
    #[pyo3(get)]
    edges: Vec<(usize, usize, String)>,
    #[pyo3(get)]
    entry: usize,
    #[pyo3(get)]
    exits: Vec<usize>,
}

impl From<FunctionCfg> for PyFunctionCfg {
    fn from(cfg: FunctionCfg) -> Self {
        Self {
            blocks: cfg.blocks.iter().map(PyBasicBlock::from).collect(),
            edges: cfg
                .edges
                .iter()
                .map(|(from, to, e)| (*from, *to, cfg_edge_name(*e).to_string()))
                .collect(),
            entry: cfg.entry,
            exits: cfg.exits,
        }
    }
}

#[pyclass(name = "Fingerprint")]
#[derive(Clone)]
struct PyFingerprint {
    #[pyo3(get)]
    name: Option<String>,
    #[pyo3(get)]
    kind: String,
    #[pyo3(get)]
    hash: u64,
    #[pyo3(get)]
    node_count: usize,
    #[pyo3(get)]
    start_byte: usize,
    #[pyo3(get)]
    end_byte: usize,
    #[pyo3(get)]
    start_line: usize,
    #[pyo3(get)]
    end_line: usize,
}

impl From<Fingerprint> for PyFingerprint {
    fn from(f: Fingerprint) -> Self {
        Self {
            name: f.name,
            kind: f.kind.to_string(),
            hash: f.hash,
            node_count: f.node_count,
            start_byte: f.start_byte,
            end_byte: f.end_byte,
            start_line: f.start_line,
            end_line: f.end_line,
        }
    }
}

#[pyclass(name = "Suppression")]
#[derive(Clone)]
struct PySuppression {
    #[pyo3(get)]
    comment_line: usize,
    #[pyo3(get)]
    target_line: Option<usize>,
    #[pyo3(get)]
    tool: String,
    #[pyo3(get)]
    rule: String,
}

impl From<Suppression> for PySuppression {
    fn from(s: Suppression) -> Self {
        Self {
            comment_line: s.comment_line,
            target_line: s.target_line,
            tool: s.tool,
            rule: s.rule,
        }
    }
}

#[pyclass(name = "IgnoredRegion")]
#[derive(Clone)]
struct PyIgnoredRegion {
    #[pyo3(get)]
    byte_range: (usize, usize),
    #[pyo3(get)]
    line_range: (usize, usize),
    #[pyo3(get)]
    tools: Option<Vec<String>>,
}

impl From<IgnoredRegion> for PyIgnoredRegion {
    fn from(r: IgnoredRegion) -> Self {
        Self {
            byte_range: (r.byte_range.start, r.byte_range.end),
            line_range: (r.line_range.start, r.line_range.end),
            tools: r.tools,
        }
    }
}

/// One document-level Markdown section: see [`crate::markdown::sections`].
/// Lines are 1-indexed and inclusive; bytes are UTF-8 offsets, end-exclusive.
#[cfg(feature = "lang-markdown")]
#[pyclass(name = "MarkdownSection")]
#[derive(Clone)]
struct PyMarkdownSection {
    #[pyo3(get)]
    level: u8,
    #[pyo3(get)]
    heading_text: String,
    #[pyo3(get)]
    start_line: usize,
    #[pyo3(get)]
    end_line: usize,
    #[pyo3(get)]
    start_byte: usize,
    #[pyo3(get)]
    end_byte: usize,
    /// Where the heading line(s) end and the body begins.
    #[pyo3(get)]
    heading_end_byte: usize,
}

#[cfg(feature = "lang-markdown")]
impl From<Section> for PyMarkdownSection {
    fn from(s: Section) -> Self {
        Self {
            level: s.level,
            start_line: s.start_line,
            end_line: s.end_line,
            start_byte: s.heading_range.start,
            end_byte: s.body_range.end,
            heading_end_byte: s.heading_range.end,
            heading_text: s.heading_text,
        }
    }
}

/// Markdown front matter: see [`crate::markdown::front_matter`]. `kind` is
/// `"yaml"` (`---`) or `"toml"` (`+++`); the body bytes exclude the
/// delimiter lines.
#[cfg(feature = "lang-markdown")]
#[pyclass(name = "FrontMatter")]
#[derive(Clone)]
struct PyFrontMatter {
    #[pyo3(get)]
    kind: &'static str,
    #[pyo3(get)]
    start_line: usize,
    #[pyo3(get)]
    end_line: usize,
    #[pyo3(get)]
    start_byte: usize,
    #[pyo3(get)]
    end_byte: usize,
    #[pyo3(get)]
    body_start_byte: usize,
    #[pyo3(get)]
    body_end_byte: usize,
}

#[cfg(feature = "lang-markdown")]
impl From<FrontMatter> for PyFrontMatter {
    fn from(f: FrontMatter) -> Self {
        Self {
            kind: match f.kind {
                FrontMatterKind::Yaml => "yaml",
                FrontMatterKind::Toml => "toml",
            },
            start_line: f.start_line,
            end_line: f.end_line,
            start_byte: f.byte_range.start,
            end_byte: f.byte_range.end,
            body_start_byte: f.body_range.start,
            body_end_byte: f.body_range.end,
        }
    }
}

/// Every node of a parsed file as parallel columns: see [`crate::flat`].
/// Each column getter returns native-endian `u32`s as `bytes`, for
/// `memoryview(col).cast("I")`; links use `NONE` (`0xFFFF_FFFF`).
///
/// `root_node` returns a [`PyNode`]: a py-tree-sitter-compatible node over the
/// same columns, implemented here so walking it costs what walking a
/// py-tree-sitter tree costs. A wrapper written in Python over the columns
/// measured 1.7-2.3x slower on clew's harvest.
#[pyclass(name = "FlatTree", frozen)]
struct PyFlatTree {
    inner: FlatTree,
    source: Py<PyBytes>,
    /// One interned Python string per kind, so `Node.type` allocates nothing.
    kind_strs: Vec<Py<PyString>>,
    /// Folded into `Node.id` so ids from two trees never collide.
    serial: u64,
}

static TREE_SERIAL: AtomicU64 = AtomicU64::new(1);

/// One node of a [`PyFlatTree`]. Answers the subset of py-tree-sitter's `Node`
/// API a tree walker needs: `type`, `children`, `named_children`,
/// `child_by_field_name`, `children_by_field_name`, `parent`, the sibling
/// links, byte and point positions, `text`, `id` and the error flags.
#[pyclass(name = "Node", frozen)]
struct PyNode {
    tree: Py<PyFlatTree>,
    row: u32,
}

impl PyNode {
    fn t(&self) -> &PyFlatTree {
        self.tree.get()
    }

    fn at(&self, py: Python<'_>, row: u32) -> Option<PyNode> {
        (row != flat::NONE).then(|| PyNode {
            tree: self.tree.clone_ref(py),
            row,
        })
    }

    fn i(&self) -> usize {
        self.row as usize
    }

    fn child_rows(&self) -> &[u32] {
        let f = &self.t().inner;
        let (lo, hi) = (f.child_offset[self.i()], f.child_offset[self.i() + 1]);
        &f.child_list[lo as usize..hi as usize]
    }

    fn flag(&self, bit: u32) -> bool {
        self.t().inner.flags[self.i()] & bit != 0
    }

    fn field_id(&self, name: &str) -> Option<u32> {
        let fields = &self.t().inner.fields;
        fields
            .iter()
            .skip(1)
            .position(|f| f == name)
            .map(|p| (p + 1) as u32)
    }

    fn step_named(&self, links: &[u32]) -> u32 {
        let flags = &self.t().inner.flags;
        let mut row = links[self.i()];
        while row != flat::NONE && flags[row as usize] & flat::FLAG_NAMED == 0 {
            row = links[row as usize];
        }
        row
    }
}

#[pymethods]
impl PyNode {
    #[getter(r#type)]
    fn kind(&self, py: Python<'_>) -> Py<PyString> {
        self.t().kind_strs[self.t().inner.kind[self.i()] as usize].clone_ref(py)
    }

    #[getter]
    fn id(&self) -> u64 {
        self.t().serial << 32 | u64::from(self.row)
    }

    #[getter]
    fn start_byte(&self) -> u32 {
        self.t().inner.start_byte[self.i()]
    }

    #[getter]
    fn end_byte(&self) -> u32 {
        self.t().inner.end_byte[self.i()]
    }

    #[getter]
    fn start_point(&self) -> (u32, u32) {
        let f = &self.t().inner;
        (f.start_row[self.i()], f.start_col[self.i()])
    }

    #[getter]
    fn end_point(&self) -> (u32, u32) {
        let f = &self.t().inner;
        (f.end_row[self.i()], f.end_col[self.i()])
    }

    #[getter]
    fn text<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        let source = self.t().source.as_bytes(py);
        let (s, e) = (self.start_byte() as usize, self.end_byte() as usize);
        PyBytes::new_bound(py, &source[s.min(source.len())..e.min(source.len())])
    }

    #[getter]
    fn is_named(&self) -> bool {
        self.flag(flat::FLAG_NAMED)
    }

    #[getter]
    fn is_error(&self) -> bool {
        self.flag(flat::FLAG_ERROR)
    }

    #[getter]
    fn is_missing(&self) -> bool {
        self.flag(flat::FLAG_MISSING)
    }

    #[getter]
    fn is_extra(&self) -> bool {
        self.flag(flat::FLAG_EXTRA)
    }

    #[getter]
    fn has_error(&self) -> bool {
        self.flag(flat::FLAG_HAS_ERROR)
    }

    #[getter]
    fn parent(&self, py: Python<'_>) -> Option<PyNode> {
        self.at(py, self.t().inner.parent[self.i()])
    }

    #[getter]
    fn prev_sibling(&self, py: Python<'_>) -> Option<PyNode> {
        self.at(py, self.t().inner.prev_sibling[self.i()])
    }

    #[getter]
    fn next_sibling(&self, py: Python<'_>) -> Option<PyNode> {
        self.at(py, self.t().inner.next_sibling[self.i()])
    }

    #[getter]
    fn prev_named_sibling(&self, py: Python<'_>) -> Option<PyNode> {
        self.at(py, self.step_named(&self.t().inner.prev_sibling))
    }

    #[getter]
    fn next_named_sibling(&self, py: Python<'_>) -> Option<PyNode> {
        self.at(py, self.step_named(&self.t().inner.next_sibling))
    }

    #[getter]
    fn children(&self, py: Python<'_>) -> Vec<PyNode> {
        self.child_rows()
            .iter()
            .filter_map(|&r| self.at(py, r))
            .collect()
    }

    #[getter]
    fn named_children(&self, py: Python<'_>) -> Vec<PyNode> {
        let flags = &self.t().inner.flags;
        self.child_rows()
            .iter()
            .filter(|&&r| flags[r as usize] & flat::FLAG_NAMED != 0)
            .filter_map(|&r| self.at(py, r))
            .collect()
    }

    #[getter]
    fn child_count(&self) -> usize {
        self.child_rows().len()
    }

    #[getter]
    fn named_child_count(&self) -> usize {
        let flags = &self.t().inner.flags;
        self.child_rows()
            .iter()
            .filter(|&&r| flags[r as usize] & flat::FLAG_NAMED != 0)
            .count()
    }

    fn child_by_field_name(&self, py: Python<'_>, name: &str) -> Option<PyNode> {
        let id = self.field_id(name)?;
        let field = &self.t().inner.field;
        let row = *self
            .child_rows()
            .iter()
            .find(|&&r| field[r as usize] == id)?;
        self.at(py, row)
    }

    fn children_by_field_name(&self, py: Python<'_>, name: &str) -> Vec<PyNode> {
        let Some(id) = self.field_id(name) else {
            return Vec::new();
        };
        let field = &self.t().inner.field;
        self.child_rows()
            .iter()
            .filter(|&&r| field[r as usize] == id)
            .filter_map(|&r| self.at(py, r))
            .collect()
    }

    fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
        other
            .downcast::<PyNode>()
            .is_ok_and(|o| o.get().row == self.row && o.get().tree.is(&self.tree))
    }

    fn __hash__(&self) -> u64 {
        self.id()
    }

    fn __repr__(&self, py: Python<'_>) -> String {
        let (s, e) = (self.start_point(), self.end_point());
        format!(
            "<Node type={}, start_point=({}, {}), end_point=({}, {})>",
            self.kind(py),
            s.0,
            s.1,
            e.0,
            e.1
        )
    }
}

fn column<'py>(py: Python<'py>, values: &[u32]) -> Bound<'py, PyBytes> {
    let mut bytes = Vec::with_capacity(values.len() * 4);
    for v in values {
        bytes.extend_from_slice(&v.to_ne_bytes());
    }
    PyBytes::new_bound(py, &bytes)
}

#[pymethods]
impl PyFlatTree {
    /// Number of nodes. Row 0 is the root.
    fn __len__(&self) -> usize {
        self.inner.len()
    }

    /// The root node (row 0).
    #[getter]
    fn root_node(slf: &Bound<'_, Self>) -> PyNode {
        PyNode {
            tree: slf.clone().unbind(),
            row: 0,
        }
    }

    /// The source bytes the tree was parsed from.
    #[getter]
    fn source(&self, py: Python<'_>) -> Py<PyBytes> {
        self.source.clone_ref(py)
    }

    /// Node-kind names, indexed by the `kind` column.
    #[getter]
    fn kinds(&self) -> Vec<String> {
        self.inner.kinds.clone()
    }

    /// Field names, indexed by the `field` column; index 0 is `""` (no field).
    #[getter]
    fn fields(&self) -> Vec<String> {
        self.inner.fields.clone()
    }

    #[getter]
    fn kind<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.kind)
    }

    #[getter]
    fn field<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.field)
    }

    /// `FLAG_*` bits: 1 named, 2 error, 4 missing, 8 extra, 16 has_error.
    #[getter]
    fn flags<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.flags)
    }

    #[getter]
    fn parent<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.parent)
    }

    #[getter]
    fn first_child<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.first_child)
    }

    #[getter]
    fn next_sibling<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.next_sibling)
    }

    #[getter]
    fn prev_sibling<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.prev_sibling)
    }

    #[getter]
    fn start_byte<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.start_byte)
    }

    #[getter]
    fn end_byte<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.end_byte)
    }

    #[getter]
    fn start_row<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.start_row)
    }

    #[getter]
    fn start_col<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.start_col)
    }

    #[getter]
    fn end_row<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.end_row)
    }

    #[getter]
    fn end_col<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.end_col)
    }

    /// `len + 1` offsets into `child_list`: row `i`'s children are
    /// `child_list[child_offset[i]:child_offset[i + 1]]`.
    #[getter]
    fn child_offset<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.child_offset)
    }

    #[getter]
    fn child_list<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        column(py, &self.inner.child_list)
    }
}

#[pyclass(name = "Capture")]
#[derive(Clone)]
struct PyCapture {
    #[pyo3(get)]
    pattern_index: usize,
    #[pyo3(get)]
    name: String,
    #[pyo3(get)]
    kind: &'static str,
    #[pyo3(get)]
    start_byte: usize,
    #[pyo3(get)]
    end_byte: usize,
    #[pyo3(get)]
    start_point: (usize, usize),
    #[pyo3(get)]
    end_point: (usize, usize),
}

impl From<Capture> for PyCapture {
    fn from(c: Capture) -> Self {
        Self {
            pattern_index: c.pattern_index,
            name: c.name,
            kind: c.kind,
            start_byte: c.start_byte,
            end_byte: c.end_byte,
            start_point: c.start_point,
            end_point: c.end_point,
        }
    }
}

/// What `classify` / `classify_file` decided, flattened for Python: `kind` is
/// one of `"empty"`, `"oversize"`, `"binary"`, `"source_text"`, and only the
/// fields that kind defines are set. A heuristic hint, never a gate: see the
/// `classify` module docs for its limits.
#[pyclass(name = "FileClass", frozen)]
#[derive(Clone)]
struct PyFileClass {
    #[pyo3(get)]
    kind: &'static str,
    /// `oversize`: the file's size in bytes.
    #[pyo3(get)]
    size: Option<u64>,
    /// `oversize`: the limit it exceeded.
    #[pyo3(get)]
    limit: Option<u64>,
    /// `binary`: `"archive"`, `"compressed"`, `"elf"`, `"pe"`, `"macho"`,
    /// `"image"`, `"pdf"`, `"document"`, `"media"`, `"font"` or `"unknown"`.
    #[pyo3(get)]
    binary_kind: Option<&'static str>,
    /// `binary`: MIME type from the magic-number match, when there was one.
    #[pyo3(get)]
    mime: Option<&'static str>,
    /// `source_text`: `"utf8"`, `"utf8_bom"`, `"utf16_le"`, `"utf16_be"` or
    /// `"latin1"`.
    #[pyo3(get)]
    encoding: Option<&'static str>,
    /// `source_text`: the file starts with a UTF-8 BOM.
    #[pyo3(get)]
    utf8_bom: bool,
    /// `source_text`: the language key the extension maps to.
    #[pyo3(get)]
    language_by_extension: Option<&'static str>,
    /// `source_text`: the language key the content suggests (shebang, `<?php`).
    #[pyo3(get)]
    language_by_content: Option<&'static str>,
}

#[pymethods]
impl PyFileClass {
    /// `True` only for `source_text`.
    #[getter]
    fn is_source_text(&self) -> bool {
        self.kind == "source_text"
    }

    /// The extension's language, else the content's.
    #[getter]
    fn likely_language(&self) -> Option<&'static str> {
        self.language_by_extension.or(self.language_by_content)
    }

    fn __repr__(&self) -> String {
        format!("<FileClass kind={}>", self.kind)
    }
}

fn binary_kind_name(kind: BinaryKind) -> &'static str {
    match kind {
        BinaryKind::Archive => "archive",
        BinaryKind::Compressed => "compressed",
        BinaryKind::Elf => "elf",
        BinaryKind::Pe => "pe",
        BinaryKind::MachO => "macho",
        BinaryKind::Image => "image",
        BinaryKind::Pdf => "pdf",
        BinaryKind::Document => "document",
        BinaryKind::Media => "media",
        BinaryKind::Font => "font",
        BinaryKind::Unknown => "unknown",
    }
}

fn encoding_name(encoding: TextEncoding) -> &'static str {
    match encoding {
        TextEncoding::Utf8 => "utf8",
        TextEncoding::Utf8Bom => "utf8_bom",
        TextEncoding::Utf16Le => "utf16_le",
        TextEncoding::Utf16Be => "utf16_be",
        TextEncoding::Latin1 => "latin1",
    }
}

impl From<FileClass> for PyFileClass {
    fn from(class: FileClass) -> Self {
        let mut out = PyFileClass {
            kind: "binary",
            size: None,
            limit: None,
            binary_kind: None,
            mime: None,
            encoding: None,
            utf8_bom: false,
            language_by_extension: None,
            language_by_content: None,
        };
        match class {
            FileClass::Empty => out.kind = "empty",
            FileClass::Oversize { size, limit } => {
                out.kind = "oversize";
                out.size = Some(size);
                out.limit = Some(limit);
            }
            FileClass::Binary { kind, mime } => {
                out.binary_kind = Some(binary_kind_name(kind));
                out.mime = mime;
            }
            FileClass::SourceText(text) => {
                out.kind = "source_text";
                out.encoding = Some(encoding_name(text.encoding));
                out.utf8_bom = text.utf8_bom;
                out.language_by_extension = text.by_extension.map(|l| l.key);
                out.language_by_content = text.by_content.map(|l| l.key);
            }
        }
        out
    }
}

/// Compiled glob ignore patterns (`toolchain.toml` `[ignore].paths` style).
#[pyclass(name = "PathIgnore", frozen)]
struct PyPathIgnore {
    inner: path_ignore::PathIgnore,
}

#[pymethods]
impl PyPathIgnore {
    /// Compile `patterns`, e.g. `["vendor/**", "third_party/**"]`. Raises
    /// `ValueError` naming the first invalid glob. With
    /// `fold_extension_case=True`, a pattern's file extension matches in any
    /// case (`*.c` ignores `A.C`) while directories stay case-sensitive.
    #[new]
    #[pyo3(signature = (patterns, fold_extension_case=false))]
    fn new(patterns: Vec<String>, fold_extension_case: bool) -> PyResult<Self> {
        let compiled = if fold_extension_case {
            path_ignore::PathIgnore::with_extension_case_folded(&patterns)
        } else {
            path_ignore::PathIgnore::new(&patterns)
        };
        compiled
            .map(|inner| Self { inner })
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }

    /// Whether `path` (relative, `/`-separated) matches any pattern.
    fn is_ignored(&self, path: &str) -> bool {
        self.inner.is_ignored(std::path::Path::new(path))
    }
}

/// Compiled-in languages, reflecting the Cargo features this wheel was built
/// with.
#[pyfunction]
fn languages() -> Vec<PyLanguageInfo> {
    registry::languages()
        .iter()
        .map(PyLanguageInfo::from)
        .collect()
}

/// Human-readable language summary, for `--supported-languages`-style flags.
#[pyfunction]
fn supported_languages_report() -> String {
    registry::supported_languages_report()
}

/// Whether a recursive walk should pick up `path`: a registered file name
/// (`CMakeLists.txt`) or a recursive-discovery extension. Path only, no I/O.
#[pyfunction]
fn is_discoverable_file(path: &str) -> bool {
    registry::is_discoverable_file(std::path::Path::new(path))
}

/// Call-graph edges for every named function/macro in `source`, parsed as
/// `language_key`.
#[pyfunction]
fn call_edges(language_key: &str, source: &str) -> PyResult<Vec<PyCallEdge>> {
    let tree = parse(language_key, source.as_bytes())?;
    Ok(calls::call_edges(tree.root_node(), source)
        .into_iter()
        .map(PyCallEdge::from)
        .collect())
}

/// Import/use-statement sources in `source`, for Ce/Ca coupling metrics.
#[pyfunction]
fn import_sources(language_key: &str, source: &[u8]) -> PyResult<Vec<String>> {
    let tree = parse(language_key, source)?;
    Ok(imports::import_sources(&tree, source, language_key))
}

/// Control-flow graph for the first function named `function_name` found in
/// `source`. Returns `None` if the language isn't modeled by `build_function_cfg`
/// (only `c`, `cpp`, `rust` today) or no matching function is found.
#[pyfunction]
fn function_cfg(
    language_key: &str,
    source: &str,
    function_name: &str,
) -> PyResult<Option<PyFunctionCfg>> {
    let tree = parse(language_key, source.as_bytes())?;
    let source_bytes = source.as_bytes();
    let target = crate::query::find_descendants(tree.root_node(), |n| {
        calls::is_function_kind(n.kind())
            && calls::get_function_name(n, source).as_deref() == Some(function_name)
    });
    Ok(target
        .into_iter()
        .find_map(|node| cfg::build_function_cfg(node, source_bytes, language_key))
        .map(PyFunctionCfg::from))
}

/// Structural fingerprints for every function-like subtree in `source`,
/// ignoring identifier/literal text (Type-2 clone detection).
#[pyfunction]
fn function_fingerprints(
    language_key: &str,
    source: &str,
    min_nodes: usize,
) -> PyResult<Vec<PyFingerprint>> {
    let tree = parse(language_key, source.as_bytes())?;
    Ok(
        fingerprint::function_fingerprints(tree.root_node(), source, min_nodes)
            .into_iter()
            .map(PyFingerprint::from)
            .collect(),
    )
}

/// `tools:suppress TOOL:RULE` single-line suppression comments in `source`.
#[pyfunction]
fn suppressions(language_key: &str, source: &str) -> PyResult<Vec<PySuppression>> {
    let sloc_mode = sloc_mode_for_key(language_key)?;
    Ok(suppressions_mod::suppressions(source, sloc_mode)
        .into_iter()
        .map(PySuppression::from)
        .collect())
}

/// Document-level sections of Markdown `source`, split at ATX and setext
/// headings. A non-blank preamble before the first heading is level 0.
#[cfg(feature = "lang-markdown")]
#[pyfunction]
fn markdown_sections(source: &str) -> PyResult<Vec<PyMarkdownSection>> {
    let tree = parse("markdown", source.as_bytes())?;
    Ok(markdown::sections(tree.root_node(), source)
        .into_iter()
        .map(PyMarkdownSection::from)
        .collect())
}

/// The `---` / `+++` front matter that opens Markdown `source`, or `None`.
#[cfg(feature = "lang-markdown")]
#[pyfunction]
fn markdown_front_matter(source: &str) -> PyResult<Option<PyFrontMatter>> {
    let tree = parse("markdown", source.as_bytes())?;
    Ok(markdown::front_matter(tree.root_node(), source).map(PyFrontMatter::from))
}

/// `tools:off` / `tools:on` ignored regions in `source`.
#[pyfunction]
fn ignored_regions(language_key: &str, source: &str) -> PyResult<Vec<PyIgnoredRegion>> {
    let sloc_mode = sloc_mode_for_key(language_key)?;
    Ok(regions::ignored_regions(source, sloc_mode)
        .into_iter()
        .map(PyIgnoredRegion::from)
        .collect())
}

/// Parse `source` (bytes) as `language_key` and return every node as a
/// `FlatTree`, whose `root_node` walks like a py-tree-sitter tree. Accepts the
/// grammar keys of `language_for_key`, so `"tsx"` selects the JSX-aware
/// TypeScript grammar.
#[pyfunction]
fn parse_tree(
    py: Python<'_>,
    language_key: &str,
    source: Bound<'_, PyBytes>,
) -> PyResult<PyFlatTree> {
    let tree = parse(language_key, source.as_bytes())?;
    let inner = flat::flatten(&tree);
    let kind_strs = inner
        .kinds
        .iter()
        .map(|k| PyString::intern_bound(py, k).unbind())
        .collect();
    Ok(PyFlatTree {
        inner,
        source: source.unbind(),
        kind_strs,
        serial: TREE_SERIAL.fetch_add(1, Ordering::Relaxed),
    })
}

/// Run a tree-sitter query over `source` and return its captures in document
/// order. Byte offsets are into `source` encoded as UTF-8. Raises `ValueError`
/// when the query does not compile against the grammar.
#[pyfunction]
fn query(language_key: &str, source: &str, query: &str) -> PyResult<Vec<PyCapture>> {
    let language = registry::language_for_key(language_key)
        .ok_or_else(|| PyValueError::new_err(format!("unknown language key: {language_key}")))?;
    let tree = parse(language_key, source.as_bytes())?;
    tsquery::run_query(&language, tree.root_node(), source.as_bytes(), query)
        .map(|caps| caps.into_iter().map(PyCapture::from).collect())
        .map_err(|e| PyValueError::new_err(e.to_string()))
}

/// The grammar's bundled tags query (definitions and references), or `None`.
#[pyfunction]
fn tags_query(language_key: &str) -> Option<String> {
    tsquery::tags_query(language_key)
}

/// Heuristically classify the file at `path` from its metadata and its first
/// `prefix_len` bytes. `max_size` (bytes) turns larger text files into
/// `oversize`; the default is no limit. Raises `OSError` when the file cannot
/// be read and for anything that is not a regular file.
#[pyfunction]
#[pyo3(signature = (path, max_size=None, prefix_len=classify_mod::DEFAULT_PREFIX_LEN))]
fn classify_file(path: &str, max_size: Option<u64>, prefix_len: usize) -> PyResult<PyFileClass> {
    let limits = ClassifyLimits {
        prefix_len,
        max_size,
    };
    classify_mod::classify_file(std::path::Path::new(path), &limits)
        .map(PyFileClass::from)
        .map_err(PyErr::from)
}

/// The I/O-free form of `classify_file`, for a caller that already holds the
/// file's leading bytes and its size.
#[pyfunction]
#[pyo3(signature = (path, prefix, file_size, max_size=None))]
fn classify(path: &str, prefix: &[u8], file_size: u64, max_size: Option<u64>) -> PyFileClass {
    let limits = ClassifyLimits {
        max_size,
        ..ClassifyLimits::default()
    };
    classify_mod::classify(std::path::Path::new(path), prefix, file_size, &limits).into()
}

#[pymodule]
fn lang_parsing_substrate(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyLanguageInfo>()?;
    m.add_class::<PyCallEdge>()?;
    m.add_class::<PyBasicBlock>()?;
    m.add_class::<PyFunctionCfg>()?;
    m.add_class::<PyFingerprint>()?;
    m.add_class::<PySuppression>()?;
    m.add_class::<PyIgnoredRegion>()?;
    m.add_class::<PyFlatTree>()?;
    m.add_class::<PyNode>()?;
    m.add_class::<PyCapture>()?;
    m.add_class::<PyFileClass>()?;
    m.add_class::<PyPathIgnore>()?;
    m.add("DEFAULT_PREFIX_LEN", classify_mod::DEFAULT_PREFIX_LEN)?;
    m.add("NONE", flat::NONE)?;
    m.add_function(wrap_pyfunction!(languages, m)?)?;
    m.add_function(wrap_pyfunction!(supported_languages_report, m)?)?;
    m.add_function(wrap_pyfunction!(is_discoverable_file, m)?)?;
    #[cfg(feature = "lang-markdown")]
    {
        m.add_class::<PyMarkdownSection>()?;
        m.add_class::<PyFrontMatter>()?;
        m.add_function(wrap_pyfunction!(markdown_sections, m)?)?;
        m.add_function(wrap_pyfunction!(markdown_front_matter, m)?)?;
    }
    m.add_function(wrap_pyfunction!(call_edges, m)?)?;
    m.add_function(wrap_pyfunction!(import_sources, m)?)?;
    m.add_function(wrap_pyfunction!(function_cfg, m)?)?;
    m.add_function(wrap_pyfunction!(function_fingerprints, m)?)?;
    m.add_function(wrap_pyfunction!(suppressions, m)?)?;
    m.add_function(wrap_pyfunction!(ignored_regions, m)?)?;
    m.add_function(wrap_pyfunction!(parse_tree, m)?)?;
    m.add_function(wrap_pyfunction!(query, m)?)?;
    m.add_function(wrap_pyfunction!(tags_query, m)?)?;
    m.add_function(wrap_pyfunction!(classify_file, m)?)?;
    m.add_function(wrap_pyfunction!(classify, m)?)?;
    Ok(())
}