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
//! Python language support.
use std::path::{Path, PathBuf};
use crate::{
ContainerBody, Import, ImportSpec, Language, LanguageSymbols, ModuleId, ModuleResolver,
Resolution, ResolverConfig, Visibility,
};
use tree_sitter::Node;
// ============================================================================
// Python language support
// ============================================================================
/// Python language support.
pub struct Python;
impl Language for Python {
fn name(&self) -> &'static str {
"Python"
}
fn extensions(&self) -> &'static [&'static str] {
&["py", "pyi", "pyw"]
}
fn grammar_name(&self) -> &'static str {
"python"
}
fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
Some(self)
}
fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
extract_docstring(node, content)
}
fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
let mut implements = Vec::new();
if let Some(superclasses) = node.child_by_field_name("superclasses") {
let mut cursor = superclasses.walk();
for child in superclasses.children(&mut cursor) {
if child.kind() == "identifier" {
implements.push(content[child.byte_range()].to_string());
}
}
}
crate::ImplementsInfo {
is_interface: false,
implements,
}
}
fn build_signature(&self, node: &Node, content: &str) -> String {
let name = match self.node_name(node, content) {
Some(n) => n,
None => {
return content[node.byte_range()]
.lines()
.next()
.unwrap_or("")
.trim()
.to_string();
}
};
if node.kind() == "class_definition" {
let bases = node
.child_by_field_name("superclasses")
.map(|b| &content[b.byte_range()])
.unwrap_or("");
if bases.is_empty() {
format!("class {}", name)
} else {
format!("class {}{}", name, bases)
}
} else {
// function_definition / decorated_definition
let is_async = node
.child(0)
.map(|c| &content[c.byte_range()] == "async")
.unwrap_or(false);
let prefix = if is_async { "async def" } else { "def" };
let params = node
.child_by_field_name("parameters")
.map(|p| &content[p.byte_range()])
.unwrap_or("()");
let return_type = node
.child_by_field_name("return_type")
.map(|r| format!(" -> {}", &content[r.byte_range()]))
.unwrap_or_default();
format!("{} {}{}{}", prefix, name, params, return_type)
}
}
fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
let line = node.start_position().row + 1;
match node.kind() {
"import_statement" => {
// import foo, import foo as bar
let mut imports = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "dotted_name" {
let module = content[child.byte_range()].to_string();
imports.push(Import {
module,
names: Vec::new(),
alias: None,
is_wildcard: false,
is_relative: false,
line,
});
} else if child.kind() == "aliased_import"
&& let Some(name) = child.child_by_field_name("name")
{
let module = content[name.byte_range()].to_string();
let alias = child
.child_by_field_name("alias")
.map(|a| content[a.byte_range()].to_string());
imports.push(Import {
module,
names: Vec::new(),
alias,
is_wildcard: false,
is_relative: false,
line,
});
}
}
imports
}
"import_from_statement" => {
// from foo import bar, baz
let module = node
.child_by_field_name("module_name")
.map(|m| content[m.byte_range()].to_string())
.unwrap_or_default();
// Check for relative import (from . or from .. or from .foo)
let text = &content[node.byte_range()];
let is_relative = text.starts_with("from .");
let mut names = Vec::new();
let mut is_wildcard = false;
let module_end = node
.child_by_field_name("module_name")
.map(|m| m.end_byte())
.unwrap_or(0);
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"dotted_name" | "identifier" if child.start_byte() > module_end => {
names.push(content[child.byte_range()].to_string());
}
"aliased_import" => {
if let Some(name) = child.child_by_field_name("name") {
names.push(content[name.byte_range()].to_string());
}
}
"wildcard_import" => {
is_wildcard = true;
}
_ => {}
}
}
vec![Import {
module,
names,
alias: None,
is_wildcard,
is_relative,
line,
}]
}
_ => Vec::new(),
}
}
fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
let names_to_use: Vec<&str> = names
.map(|n| n.to_vec())
.unwrap_or_else(|| import.names.iter().map(|s| s.as_str()).collect());
if import.is_wildcard {
format!("from {} import *", import.module)
} else if names_to_use.is_empty() {
if let Some(ref alias) = import.alias {
format!("import {} as {}", import.module, alias)
} else {
format!("import {}", import.module)
}
} else {
format!("from {} import {}", import.module, names_to_use.join(", "))
}
}
fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
extract_decorators(node, content)
}
fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
if let Some(name) = self.node_name(node, content) {
if name.starts_with("__") && name.ends_with("__") {
Visibility::Public // dunder methods
} else if name.starts_with("__") {
Visibility::Private // name mangled
} else if name.starts_with('_') {
Visibility::Protected // convention private
} else {
Visibility::Public
}
} else {
Visibility::Public
}
}
fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
let name = symbol.name.as_str();
match symbol.kind {
crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
crate::SymbolKind::Class => name.starts_with("Test") && name.len() > 4,
crate::SymbolKind::Module => name == "tests" || name == "test" || name == "__tests__",
_ => false,
}
}
fn test_file_globs(&self) -> &'static [&'static str] {
&["**/test_*.py", "**/*_test.py"]
}
fn extract_module_doc(&self, src: &str) -> Option<String> {
extract_python_module_doc(src)
}
fn body_has_docstring(&self, body: &Node, content: &str) -> bool {
let _ = content;
body.child(0)
.map(|c| {
c.kind() == "string"
|| (c.kind() == "expression_statement"
&& c.child(0).map(|n| n.kind() == "string").unwrap_or(false))
})
.unwrap_or(false)
}
fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
node.child_by_field_name("body")
}
fn analyze_container_body(
&self,
body_node: &Node,
content: &str,
inner_indent: &str,
) -> Option<ContainerBody> {
let mut cursor = body_node.walk();
let children: Vec<_> = body_node.children(&mut cursor).collect();
if children.is_empty() {
return Some(ContainerBody {
content_start: body_node.start_byte(),
content_end: body_node.end_byte(),
inner_indent: inner_indent.to_string(),
is_empty: true,
});
}
let mut first_real_idx = 0;
for (i, child) in children.iter().enumerate() {
let is_docstring = if child.kind() == "expression_statement" {
let mut child_cursor = child.walk();
child
.children(&mut child_cursor)
.next()
.map(|fc| fc.kind() == "string")
.unwrap_or(false)
} else {
child.kind() == "string"
};
if is_docstring && i == 0 {
first_real_idx = i + 1;
continue;
}
break;
}
let is_empty = children.iter().skip(first_real_idx).all(|c| {
c.kind() == "pass_statement"
|| c.kind() == "string"
|| (c.kind() == "expression_statement"
&& c.child(0).map(|fc| fc.kind() == "string").unwrap_or(false))
});
let content_start = if first_real_idx < children.len() {
let child_start = children[first_real_idx].start_byte();
content[..child_start]
.rfind('\n')
.map(|i| i + 1)
.unwrap_or(child_start)
} else if !children.is_empty() {
// normalize-syntax-allow: rust/unwrap-in-impl - !children.is_empty() guarantees last() is Some
let last_end = children.last().unwrap().end_byte();
if last_end < content.len() && content.as_bytes()[last_end] == b'\n' {
last_end + 1
} else {
last_end
}
} else {
body_node.start_byte()
};
Some(ContainerBody {
content_start,
content_end: body_node.end_byte(),
inner_indent: inner_indent.to_string(),
is_empty,
})
}
fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
static RESOLVER: PythonModuleResolver = PythonModuleResolver;
Some(&RESOLVER)
}
}
impl LanguageSymbols for Python {}
// =============================================================================
// Python Module Resolver
// =============================================================================
/// Module resolver for Python.
///
/// Handles:
/// - Relative imports (`from . import foo`, `from ..utils import bar`)
/// - Absolute imports against workspace root and `src/` layout
/// - `pyproject.toml` / `setup.cfg` discovery for package roots
pub struct PythonModuleResolver;
impl ModuleResolver for PythonModuleResolver {
fn workspace_config(&self, root: &Path) -> ResolverConfig {
let mut search_roots: Vec<PathBuf> = Vec::new();
// Detect src/ layout
let src_dir = root.join("src");
if src_dir.is_dir() {
search_roots.push(src_dir);
}
ResolverConfig {
workspace_root: root.to_path_buf(),
path_mappings: Vec::new(),
search_roots,
}
}
fn module_of_file(&self, _root: &Path, file: &Path, cfg: &ResolverConfig) -> Vec<ModuleId> {
let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(ext, "py" | "pyi" | "pyw") {
return Vec::new();
}
// Find the package root: walk up from file's directory looking for __init__.py
let file_dir = match file.parent() {
Some(d) => d,
None => return Vec::new(),
};
// Find the topmost directory that is still a package (has __init__.py)
// by walking up until we hit a dir without __init__.py or the workspace root.
let root = &cfg.workspace_root;
// Start from file_dir and find the package root
let package_root = find_package_root(file_dir, root, &cfg.search_roots);
let rel = file.strip_prefix(&package_root).unwrap_or(file);
let components: Vec<&str> = rel
.components()
.filter_map(|c| {
if let std::path::Component::Normal(s) = c {
s.to_str()
} else {
None
}
})
.collect();
if components.is_empty() {
return Vec::new();
}
let last = *components.last().unwrap();
let module_path = if last == "__init__.py" {
// Package itself
if components.len() == 1 {
return Vec::new(); // top-level __init__.py with no package name
}
components[..components.len() - 1].join(".")
} else {
let stem = last.strip_suffix(".py").unwrap_or(last);
let mut parts: Vec<&str> = components[..components.len() - 1].to_vec();
parts.push(stem);
parts.join(".")
};
if module_path.is_empty() {
return Vec::new();
}
vec![ModuleId {
canonical_path: module_path,
}]
}
fn resolve(&self, from_file: &Path, spec: &ImportSpec, cfg: &ResolverConfig) -> Resolution {
let ext = from_file.extension().and_then(|e| e.to_str()).unwrap_or("");
if !matches!(ext, "py" | "pyi" | "pyw") {
return Resolution::NotApplicable;
}
let raw = &spec.raw;
// 1. Relative imports (is_relative or raw starts with dots — counted by caller)
if spec.is_relative {
return resolve_python_relative(from_file, raw, cfg);
}
// 2. Absolute imports: search workspace root and src/ search roots
let search_bases: Vec<PathBuf> = std::iter::once(cfg.workspace_root.clone())
.chain(cfg.search_roots.iter().cloned())
.collect();
let module_rel = raw.replace('.', "/");
for base in &search_bases {
// Try module/path.py
let as_file = base.join(format!("{}.py", module_rel));
if as_file.exists() {
let exported_name = spec.names.first().cloned().unwrap_or_default();
return Resolution::Resolved(as_file, exported_name);
}
// Try module/path/__init__.py
let as_pkg = base.join(&module_rel).join("__init__.py");
if as_pkg.exists() {
let exported_name = spec.names.first().cloned().unwrap_or_default();
return Resolution::Resolved(as_pkg, exported_name);
}
}
Resolution::NotFound
}
}
/// Find the topmost package root for a file.
/// Returns the first ancestor directory that does NOT have an `__init__.py`
/// (i.e., the directory containing the top-level package dir).
fn find_package_root(file_dir: &Path, workspace_root: &Path, search_roots: &[PathBuf]) -> PathBuf {
// If file is under a search root, use that as the base
for sr in search_roots {
if file_dir.starts_with(sr) {
return sr.clone();
}
}
// Walk up from file_dir until we find a dir without __init__.py
let mut current = file_dir.to_path_buf();
let mut last_package_parent = workspace_root.to_path_buf();
loop {
if current.join("__init__.py").exists() {
if let Some(parent) = current.parent() {
last_package_parent = parent.to_path_buf();
if parent == workspace_root || !parent.starts_with(workspace_root) {
break;
}
current = parent.to_path_buf();
} else {
break;
}
} else {
// This directory is not a package — it's the package root
last_package_parent = current.clone();
break;
}
}
last_package_parent
}
/// Resolve a relative Python import.
///
/// `from . import foo` → `spec.raw = ""`, `spec.names = ["foo"]`, `is_relative = true`
/// `from .utils import bar` → `spec.raw = "utils"`, `is_relative = true`
/// `from ..pkg import x` → `spec.raw = "..pkg"` (or similar)
fn resolve_python_relative(from_file: &Path, raw: &str, _cfg: &ResolverConfig) -> Resolution {
let file_dir = match from_file.parent() {
Some(d) => d,
None => return Resolution::NotFound,
};
// Count leading dots to determine how many levels up to go
let dot_count = raw.chars().take_while(|&c| c == '.').count();
let module_part = &raw[dot_count..];
// Go up (dot_count - 1) levels from file_dir (1 dot = same dir)
let mut base = file_dir.to_path_buf();
for _ in 1..dot_count {
base = match base.parent() {
Some(p) => p.to_path_buf(),
None => return Resolution::NotFound,
};
}
if module_part.is_empty() {
// `from . import foo` — look in base dir for each name
return Resolution::NotFound; // can't resolve without knowing the names here
}
let module_rel = module_part.replace('.', "/");
// Try module_part.py
let as_file = base.join(format!("{}.py", module_rel));
if as_file.exists() {
return Resolution::Resolved(as_file, String::new());
}
// Try module_part/__init__.py
let as_pkg = base.join(&module_rel).join("__init__.py");
if as_pkg.exists() {
return Resolution::Resolved(as_pkg, String::new());
}
Resolution::NotFound
}
/// Extract the module-level docstring from Python source.
///
/// Skips shebang lines and coding-declaration comments, then looks for a
/// triple-quoted string as the first non-comment, non-blank content.
fn extract_python_module_doc(src: &str) -> Option<String> {
let mut lines = src.lines().peekable();
// Skip shebang and coding comments (PEP 263)
loop {
match lines.peek() {
Some(line) => {
let t = line.trim();
if t.starts_with("#!") || t.starts_with("# -*-") || t.starts_with("# coding") {
lines.next();
} else {
break;
}
}
None => return None,
}
}
let remaining: String = lines.collect::<Vec<_>>().join("\n");
let trimmed = remaining.trim_start();
// Must start with triple-quote string
let (quote, rest) = if let Some(rest) = trimmed.strip_prefix("\"\"\"") {
("\"\"\"", rest)
} else if let Some(rest) = trimmed.strip_prefix("'''") {
("'''", rest)
} else {
return None;
};
// Find the closing triple-quote
let end = rest.find(quote)?;
let doc = rest[..end].trim();
if doc.is_empty() {
None
} else {
Some(doc.to_string())
}
}
/// Extract a Python docstring from a function or class body.
///
/// Looks for the first statement in the body being a string literal.
/// Handles both old grammar style (expression_statement > string) and
/// new arborium style (string directly, with string_content child).
fn extract_docstring(node: &Node, content: &str) -> Option<String> {
let body = node.child_by_field_name("body")?;
let first = body.child(0)?;
// Handle both grammar versions:
// - Old: expression_statement > string
// - New (arborium): string directly, with string_content child
let string_node = match first.kind() {
"string" => Some(first),
"expression_statement" => first.child(0).filter(|n| n.kind() == "string"),
_ => None,
}?;
// Try string_content child (arborium style)
let mut cursor = string_node.walk();
for child in string_node.children(&mut cursor) {
if child.kind() == "string_content" {
let doc = content[child.byte_range()].trim();
if !doc.is_empty() {
return Some(doc.to_string());
}
}
}
// Fallback: extract from full string text (old style)
let text = &content[string_node.byte_range()];
let doc = text
.trim_start_matches("\"\"\"")
.trim_start_matches("'''")
.trim_start_matches('"')
.trim_start_matches('\'')
.trim_end_matches("\"\"\"")
.trim_end_matches("'''")
.trim_end_matches('"')
.trim_end_matches('\'')
.trim();
if !doc.is_empty() {
Some(doc.to_string())
} else {
None
}
}
/// Extract decorators from a Python definition node.
/// Python wraps decorated definitions in a `decorated_definition` parent node.
/// The node passed here is `function_definition` or `class_definition`,
/// so we look at the parent for `decorator` siblings.
fn extract_decorators(node: &Node, content: &str) -> Vec<String> {
let mut attrs = Vec::new();
if let Some(parent) = node.parent()
&& parent.kind() == "decorated_definition"
{
let mut cursor = parent.walk();
for child in parent.children(&mut cursor) {
if child.kind() == "decorator" {
attrs.push(content[child.byte_range()].to_string());
}
}
}
attrs
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GrammarLoader;
use tree_sitter::Parser;
struct ParseResult {
tree: tree_sitter::Tree,
#[allow(dead_code)]
loader: GrammarLoader,
}
fn parse_python(content: &str) -> ParseResult {
let loader = GrammarLoader::new();
let language = loader.get("python").ok().unwrap();
let mut parser = Parser::new();
parser.set_language(&language).unwrap();
ParseResult {
tree: parser.parse(content, None).unwrap(),
loader,
}
}
#[test]
fn test_python_extract_function() {
let support = Python;
let content = r#"def foo(x: int) -> str:
"""Convert to string."""
return str(x)
"#;
let result = parse_python(content);
let root = result.tree.root_node();
// Find function node
let mut cursor = root.walk();
let func = root
.children(&mut cursor)
.find(|n| n.kind() == "function_definition")
.unwrap();
let sig = support.build_signature(&func, content);
let doc = support.extract_docstring(&func, content);
assert_eq!(support.node_name(&func, content), Some("foo"));
assert!(sig.contains("def foo(x: int) -> str"));
assert_eq!(doc, Some("Convert to string.".to_string()));
}
#[test]
fn test_python_extract_class() {
let support = Python;
let content = r#"class Foo(Bar):
"""A foo class."""
pass
"#;
let result = parse_python(content);
let root = result.tree.root_node();
let mut cursor = root.walk();
let class = root
.children(&mut cursor)
.find(|n| n.kind() == "class_definition")
.unwrap();
let sig = support.build_signature(&class, content);
let doc = support.extract_docstring(&class, content);
assert_eq!(support.node_name(&class, content), Some("Foo"));
assert!(sig.contains("class Foo(Bar)"));
assert_eq!(doc, Some("A foo class.".to_string()));
}
#[test]
fn test_python_visibility() {
let support = Python;
let content = r#"def public(): pass
def _protected(): pass
def __private(): pass
def __dunder__(): pass
"#;
let result = parse_python(content);
let root = result.tree.root_node();
let mut cursor = root.walk();
let funcs: Vec<_> = root
.children(&mut cursor)
.filter(|n| n.kind() == "function_definition")
.collect();
assert_eq!(
support.get_visibility(&funcs[0], content),
Visibility::Public
);
assert_eq!(
support.get_visibility(&funcs[1], content),
Visibility::Protected
);
assert_eq!(
support.get_visibility(&funcs[2], content),
Visibility::Private
);
assert_eq!(
support.get_visibility(&funcs[3], content),
Visibility::Public
); // dunder
}
/// Documents node kinds that exist in the Python grammar but aren't used in trait methods.
/// Each exclusion has a reason. Review periodically as features expand.
///
/// Run `cross_check_node_kinds` in registry.rs to see all potentially useful kinds.
#[test]
fn unused_node_kinds_audit() {
use crate::validate_unused_kinds_audit;
// Categories:
// - STRUCTURAL: Internal/wrapper nodes, not semantically meaningful on their own
// - CLAUSE: Sub-parts of statements, handled via parent (e.g., else_clause in if_statement)
// - EXPRESSION: Expressions don't create control flow/scope, we track statements
// - TYPE: Type annotation nodes, not relevant for current analysis
// - LEGACY: Python 2 compatibility, not worth supporting
// - OPERATOR: Operators within expressions, too granular
// - MAYBE: Potentially useful, to be added when needed
#[rustfmt::skip]
let documented_unused: &[&str] = &[
// STRUCTURAL
"aliased_import", // used internally by extract_imports
"block", // generic block wrapper (duplicate in grammar)
"expression_list", // comma-separated expressions // too common, used everywhere
"import_prefix", // dots in relative imports
"lambda_parameters", // internal to lambda // root node of file
"parenthesized_expression",// grouping only
"relative_import", // handled in extract_imports
"tuple_expression", // comma-separated values
"wildcard_import", // handled in extract_imports
// CLAUSE (sub-parts of statements)
"case_pattern", // internal to case_clause
"class_pattern", // pattern in match/case
"elif_clause", // part of if_statement
"else_clause", // part of if/for/while/try
"finally_clause", // part of try_statement
"for_in_clause", // internal to comprehensions
"if_clause", // internal to comprehensions
"with_clause", // internal to with_statement
"with_item", // internal to with_statement
// EXPRESSION (don't affect control flow structure)
"await", // await keyword, not a statement
"format_expression", // f-string interpolation
"format_specifier", // f-string format spec
"named_expression", // walrus operator :=
"yield", // yield keyword form
// TYPE (type annotations)
"constrained_type", // type constraints
"generic_type", // parameterized types
"member_type", // attribute access in types
"splat_type", // *args/**kwargs types
"type", // generic type node
"type_alias_statement", // could track as symbol
"type_conversion", // !r/!s/!a in f-strings
"type_parameter", // generic type params
"typed_default_parameter", // param with type and default
"typed_parameter", // param with type annotation
"union_type", // X | Y union syntax
// OPERATOR
"binary_operator", // +, -, *, /, etc.
"boolean_operator", // and/or - handled in complexity_nodes as keywords
"comparison_operator", // ==, <, >, etc.
"not_operator", // not keyword
"unary_operator", // -, +, ~
// LEGACY (Python 2)
"exec_statement", // Python 2 exec
"print_statement", // Python 2 print
// MAYBE: Potentially useful
"decorated_definition", // wrapper for @decorator
"delete_statement", // del statement
"future_import_statement", // from __future__
"global_statement", // scope modifier
"nonlocal_statement", // scope modifier
"pass_statement", // no-op, detect empty bodies
// control flow — not extracted as symbols
"lambda",
"import_statement",
"continue_statement",
"raise_statement",
"case_clause",
"generator_expression",
"assert_statement",
"if_statement",
"while_statement",
"with_statement",
"try_statement",
"import_from_statement",
"return_statement",
"except_clause",
"dictionary_comprehension",
"conditional_expression",
"match_statement",
"set_comprehension",
"for_statement",
"list_comprehension",
"break_statement",
];
validate_unused_kinds_audit(&Python, documented_unused)
.expect("Python unused node kinds audit failed");
}
}