1use std::collections::{HashMap, HashSet};
2use std::ffi::OsStr;
3use std::path::{Component, Path, PathBuf};
4
5use ignore::WalkBuilder;
6
7use crate::map::{Edge, Field, Group, Part, Structure, Unit, Unparsed, Unresolved};
8
9const EXCLUDED_DIRS: &[&str] = &[
10 "tests",
11 "test",
12 ".venv",
13 "venv",
14 "__pycache__",
15 "node_modules",
16];
17
18const PYTHON_KEYWORDS: &[&str] = &[
19 "False", "None", "True", "and", "as", "assert", "async", "await", "break", "case", "class",
20 "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if",
21 "import", "in", "is", "lambda", "match", "nonlocal", "not", "or", "pass", "raise", "return",
22 "try", "while", "with", "yield",
23];
24
25struct PyUnitInfo {
26 id: String,
27 group_id: String,
28 file_rel: String,
29 package_segs: Vec<String>,
30 is_init: bool,
31 abs_path: PathBuf,
32}
33
34struct LogicalLine {
35 line: u32,
36 indent: usize,
37 text: String,
38}
39
40enum FromItem {
41 Wildcard,
42 Name { orig: String, local: String },
43}
44
45enum ParsedImport {
46 Import {
47 line: u32,
48 module: String,
49 alias: String,
50 },
51 From {
52 line: u32,
53 dots: usize,
54 module: String,
55 items: Vec<FromItem>,
56 },
57}
58
59struct UnitScan {
60 unit_id: String,
61 stripped: String,
62 direct_from_names: Vec<(String, String)>,
63 module_aliases: Vec<(String, String)>,
64}
65
66pub fn extract(root: &Path) -> Result<Part, String> {
67 let py_files = discover_python_files(root);
68 if py_files.is_empty() {
69 return Ok(Part::default());
70 }
71
72 let mut unit_infos: Vec<PyUnitInfo> = Vec::with_capacity(py_files.len());
73 let mut units: Vec<Unit> = Vec::with_capacity(py_files.len());
74 let mut groups_map: HashMap<(String, String), Group> = HashMap::new();
75 let mut unit_set: HashSet<String> = HashSet::new();
76 let mut unit_to_file: HashMap<String, String> = HashMap::new();
77 let mut unit_to_group: HashMap<String, String> = HashMap::new();
78 let mut init_units: HashSet<String> = HashSet::new();
79 let mut top_level_names: HashSet<String> = HashSet::new();
80
81 for rel in py_files {
82 let Some(info) = build_unit_info(root, &rel) else {
83 continue;
84 };
85
86 if let Some(existing) = unit_to_file.insert(info.id.clone(), info.file_rel.clone()) {
87 let (first, second) = if existing <= info.file_rel {
88 (existing, info.file_rel)
89 } else {
90 (info.file_rel, existing)
91 };
92 return Err(format!(
93 "two Python files have the module name {}: {} and {}",
94 info.id, first, second
95 ));
96 }
97
98 let group_path = dir_rel_to_string(rel.parent().unwrap_or_else(|| Path::new("")));
99 groups_map
100 .entry((info.group_id.clone(), group_path.clone()))
101 .or_insert_with(|| Group {
102 id: info.group_id.clone(),
103 kind: "package".to_string(),
104 path: group_path,
105 lang: "python".to_string(),
106 });
107
108 if let Some(first) = info.id.split('.').next() {
109 if !first.is_empty() {
110 top_level_names.insert(first.to_string());
111 }
112 }
113 if info.is_init {
114 init_units.insert(info.id.clone());
115 }
116 unit_set.insert(info.id.clone());
117 unit_to_group.insert(info.id.clone(), info.group_id.clone());
118
119 units.push(Unit {
120 id: info.id.clone(),
121 group: info.group_id.clone(),
122 file: info.file_rel.clone(),
123 lang: "python".to_string(),
124 });
125 unit_infos.push(info);
126 }
127
128 let mut edges: Vec<Edge> = Vec::new();
129 let mut structures: Vec<Structure> = Vec::new();
130 let mut unparsed: Vec<Unparsed> = Vec::new();
131 let mut unresolved: Vec<Unresolved> = Vec::new();
132 let mut scans: Vec<UnitScan> = Vec::with_capacity(unit_infos.len());
133 let mut init_reexports: HashMap<(String, String), Vec<(String, String)>> = HashMap::new();
134
135 for info in &unit_infos {
136 let bytes = std::fs::read(&info.abs_path)
137 .map_err(|e| format!("cannot read {}: {e}", info.abs_path.display()))?;
138 let src = match String::from_utf8(bytes) {
139 Ok(s) => s,
140 Err(e) => {
141 unparsed.push(Unparsed {
142 file: info.file_rel.clone(),
143 reason: e.to_string(),
144 });
145 continue;
146 }
147 };
148
149 let stripped = blank_strings_and_comments(&src);
150 let logical_lines = join_logical_lines(&stripped);
151
152 let file_structures = extract_structures(&logical_lines, &info.id, &info.file_rel);
153 structures.extend(file_structures);
154
155 let parsed_imports = parse_imports(&logical_lines);
156 let mut direct_from_names: Vec<(String, String)> = Vec::new();
157 let mut module_aliases: Vec<(String, String)> = Vec::new();
158
159 for imp in parsed_imports {
160 match imp {
161 ParsedImport::Import {
162 line,
163 module,
164 alias,
165 } => {
166 if let Some(target_unit) =
167 resolve_plain_import(&module, &info.package_segs, &unit_set)
168 {
169 emit_edges(&info.id, &target_unit, &unit_to_group, &mut edges);
170 module_aliases.push((target_unit, alias));
171 } else if first_segment_in(&module, &top_level_names) {
172 unresolved.push(Unresolved {
173 file: info.file_rel.clone(),
174 line,
175 reference: module,
176 });
177 }
178 }
179 ParsedImport::From {
180 line,
181 dots,
182 module,
183 items,
184 } => {
185 resolve_from_import(
186 info,
187 line,
188 dots,
189 &module,
190 &items,
191 &unit_set,
192 &top_level_names,
193 &unit_to_group,
194 &mut edges,
195 &mut unresolved,
196 &mut direct_from_names,
197 &mut module_aliases,
198 &mut init_reexports,
199 );
200 }
201 }
202 }
203
204 scans.push(UnitScan {
205 unit_id: info.id.clone(),
206 stripped,
207 direct_from_names,
208 module_aliases,
209 });
210 }
211
212 let mut struct_by_unit_name: HashMap<(String, String), usize> = HashMap::new();
213 let mut structs_by_unit: HashMap<String, Vec<usize>> = HashMap::new();
214 for (idx, s) in structures.iter().enumerate() {
215 struct_by_unit_name.insert((s.unit.clone(), s.name.clone()), idx);
216 structs_by_unit.entry(s.unit.clone()).or_default().push(idx);
217 }
218
219 for scan in &scans {
220 for (target_unit, orig_name) in &scan.direct_from_names {
221 if let Some(&idx) = struct_by_unit_name.get(&(target_unit.clone(), orig_name.clone())) {
222 if structures[idx].unit != scan.unit_id {
223 structures[idx].referenced_by.push(scan.unit_id.clone());
224 }
225 }
226 if init_units.contains(target_unit) {
227 if let Some(targets) = init_reexports.get(&(target_unit.clone(), orig_name.clone()))
228 {
229 for (real_unit, real_name) in targets {
230 if let Some(&idx) =
231 struct_by_unit_name.get(&(real_unit.clone(), real_name.clone()))
232 {
233 if structures[idx].unit != scan.unit_id {
234 structures[idx].referenced_by.push(scan.unit_id.clone());
235 }
236 }
237 }
238 }
239 }
240 }
241
242 for (target_unit, alias_name) in &scan.module_aliases {
243 if let Some(indices) = structs_by_unit.get(target_unit) {
244 for &idx in indices {
245 if structures[idx].unit != scan.unit_id
246 && code_contains_attr_ref(&scan.stripped, alias_name, &structures[idx].name)
247 {
248 structures[idx].referenced_by.push(scan.unit_id.clone());
249 }
250 }
251 }
252 }
253 }
254
255 let groups: Vec<Group> = groups_map.into_values().collect();
256
257 Ok(Part {
258 groups,
259 units,
260 edges,
261 structures,
262 unparsed,
263 unresolved,
264 })
265}
266
267fn discover_python_files(root: &Path) -> Vec<PathBuf> {
268 let mut walk = WalkBuilder::new(root);
269 walk.require_git(false);
270 walk.parents(false);
271 walk.filter_entry(|entry| {
272 if entry.depth() == 0 {
273 return true;
274 }
275 if entry.file_type().is_some_and(|t| t.is_dir()) {
276 if let Some(name) = entry.file_name().to_str() {
277 if EXCLUDED_DIRS.contains(&name) {
278 return false;
279 }
280 }
281 }
282 true
283 });
284 walk.sort_by_file_path(|a, b| a.cmp(b));
285
286 let mut files = Vec::new();
287 for entry in walk.build() {
288 let Ok(entry) = entry else { continue };
289 if !entry.file_type().is_some_and(|t| t.is_file()) {
290 continue;
291 }
292 let path = entry.path();
293 if path.extension() != Some(OsStr::new("py")) {
294 continue;
295 }
296 let Some(file_name) = path.file_name().and_then(|s| s.to_str()) else {
297 continue;
298 };
299 if is_excluded_py_file(file_name) {
300 continue;
301 }
302 let Ok(rel) = path.strip_prefix(root) else {
303 continue;
304 };
305 if has_excluded_dir_component(rel) {
306 continue;
307 }
308 files.push(rel.to_path_buf());
309 }
310 files
311}
312
313fn is_excluded_py_file(name: &str) -> bool {
314 name == "conftest.py"
315 || (name.starts_with("test_") && name.ends_with(".py"))
316 || name.ends_with("_test.py")
317}
318
319fn has_excluded_dir_component(rel: &Path) -> bool {
320 let Some(parent) = rel.parent() else {
321 return false;
322 };
323 for comp in parent.components() {
324 if let Component::Normal(s) = comp {
325 if let Some(name) = s.to_str() {
326 if EXCLUDED_DIRS.contains(&name) {
327 return true;
328 }
329 }
330 }
331 }
332 false
333}
334
335fn build_unit_info(root: &Path, rel: &Path) -> Option<PyUnitInfo> {
336 let stem = rel.file_stem()?.to_str()?.to_string();
337 let parent = rel.parent().unwrap_or_else(|| Path::new(""));
338 let all_dir_segs: Vec<String> = parent
339 .components()
340 .filter_map(|c| match c {
341 Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
342 _ => None,
343 })
344 .collect();
345
346 let dir_segs: Vec<String> = match all_dir_segs.iter().rposition(|s| s == "src") {
347 Some(idx) => all_dir_segs[idx + 1..].to_vec(),
348 None => all_dir_segs.clone(),
349 };
350
351 let group_id = if !dir_segs.is_empty() {
352 dir_segs.join(".")
353 } else if !all_dir_segs.is_empty() {
354 all_dir_segs.join(".")
355 } else {
356 ".".to_string()
357 };
358
359 let is_init = stem == "__init__";
360 let id = if is_init {
361 if dir_segs.is_empty() {
362 stem
363 } else {
364 dir_segs.join(".")
365 }
366 } else if dir_segs.is_empty() {
367 stem
368 } else {
369 format!("{}.{stem}", dir_segs.join("."))
370 };
371
372 let file_rel = path_rel_to_string(rel);
373
374 Some(PyUnitInfo {
375 id,
376 group_id,
377 file_rel,
378 package_segs: dir_segs,
379 is_init,
380 abs_path: root.join(rel),
381 })
382}
383
384fn path_rel_to_string(rel: &Path) -> String {
385 let parts: Vec<String> = rel
386 .components()
387 .filter_map(|c| match c {
388 Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
389 _ => None,
390 })
391 .collect();
392 parts.join("/")
393}
394
395fn dir_rel_to_string(rel: &Path) -> String {
396 let s = path_rel_to_string(rel);
397 if s.is_empty() {
398 ".".to_string()
399 } else {
400 s
401 }
402}
403
404fn blank_strings_and_comments(src: &str) -> String {
405 let normalized = src.replace("\r\n", "\n").replace('\r', "\n");
406 let chars: Vec<char> = normalized.chars().collect();
407 let n = chars.len();
408 let mut out = String::with_capacity(normalized.len());
409 let mut i = 0;
410
411 while i < n {
412 let c = chars[i];
413 if c == '#' {
414 while i < n && chars[i] != '\n' {
415 out.push(' ');
416 i += 1;
417 }
418 continue;
419 }
420
421 if let Some((prefix_len, quote)) = string_start(&chars, i) {
422 for _ in 0..prefix_len {
423 out.push(' ');
424 }
425 i += prefix_len;
426
427 let is_triple = i + 2 < n && chars[i + 1] == quote && chars[i + 2] == quote;
428 if is_triple {
429 out.push_str(" ");
430 i += 3;
431 while i < n {
432 if chars[i] == '\\' {
433 out.push(' ');
434 i += 1;
435 if i < n {
436 if chars[i] == '\n' {
437 out.push('\n');
438 } else {
439 out.push(' ');
440 }
441 i += 1;
442 }
443 } else if i + 2 < n
444 && chars[i] == quote
445 && chars[i + 1] == quote
446 && chars[i + 2] == quote
447 {
448 out.push_str(" ");
449 i += 3;
450 break;
451 } else if chars[i] == '\n' {
452 out.push('\n');
453 i += 1;
454 } else {
455 out.push(' ');
456 i += 1;
457 }
458 }
459 } else {
460 out.push(quote);
461 i += 1;
462 let mut multiline = false;
463 while i < n {
464 if chars[i] == '\\' {
465 out.push(' ');
466 i += 1;
467 if i < n {
468 if chars[i] == '\n' {
469 out.push('\n');
470 multiline = true;
471 } else {
472 out.push(' ');
473 }
474 i += 1;
475 }
476 } else if chars[i] == quote {
477 if multiline {
478 out.push(' ');
479 } else {
480 out.push(quote);
481 }
482 i += 1;
483 break;
484 } else if chars[i] == '\n' {
485 out.push('\n');
486 i += 1;
487 break;
488 } else {
489 out.push(' ');
490 i += 1;
491 }
492 }
493 }
494 continue;
495 }
496
497 out.push(c);
498 i += 1;
499 }
500
501 out
502}
503
504fn string_start(chars: &[char], i: usize) -> Option<(usize, char)> {
505 let n = chars.len();
506 let c = chars[i];
507 if c == '"' || c == '\'' {
508 return Some((0, c));
509 }
510 if i > 0 && is_ident_continue(chars[i - 1]) {
511 return None;
512 }
513 if i + 2 < n
514 && (chars[i + 2] == '"' || chars[i + 2] == '\'')
515 && is_two_char_string_prefix(c, chars[i + 1])
516 {
517 return Some((2, chars[i + 2]));
518 }
519 if i + 1 < n && (chars[i + 1] == '"' || chars[i + 1] == '\'') && is_one_char_string_prefix(c) {
520 return Some((1, chars[i + 1]));
521 }
522 None
523}
524
525fn is_one_char_string_prefix(c: char) -> bool {
526 matches!(c, 'r' | 'R' | 'u' | 'U' | 'b' | 'B' | 'f' | 'F')
527}
528
529fn is_two_char_string_prefix(a: char, b: char) -> bool {
530 matches!(
531 (a.to_ascii_lowercase(), b.to_ascii_lowercase()),
532 ('r', 'b') | ('b', 'r') | ('r', 'f') | ('f', 'r')
533 )
534}
535
536fn measure_indent(line: &str) -> usize {
537 let mut width = 0;
538 for ch in line.chars() {
539 match ch {
540 ' ' => width += 1,
541 '\t' => width += 4,
542 _ => break,
543 }
544 }
545 width
546}
547
548fn join_logical_lines(stripped: &str) -> Vec<LogicalLine> {
549 let mut result = Vec::new();
550 let mut cur_line: u32 = 0;
551 let mut cur_indent: usize = 0;
552 let mut cur_text = String::new();
553 let mut depth: usize = 0;
554 let mut continuing = false;
555
556 for (idx, raw_line) in stripped.split('\n').enumerate() {
557 let line_no = (idx + 1) as u32;
558 if !continuing {
559 if raw_line.trim().is_empty() {
560 continue;
561 }
562 cur_line = line_no;
563 cur_indent = measure_indent(raw_line);
564 cur_text.clear();
565 depth = 0;
566 }
567
568 let trimmed_end = raw_line.trim_end();
569 let has_backslash = trimmed_end.ends_with('\\');
570 let piece = if has_backslash {
571 trimmed_end[..trimmed_end.len() - 1].trim()
572 } else {
573 raw_line.trim()
574 };
575
576 if !piece.is_empty() {
577 if !cur_text.is_empty() {
578 cur_text.push(' ');
579 }
580 cur_text.push_str(piece);
581 for ch in piece.chars() {
582 match ch {
583 '(' | '[' | '{' => depth += 1,
584 ')' | ']' | '}' => depth = depth.saturating_sub(1),
585 _ => {}
586 }
587 }
588 }
589
590 if depth > 0 || has_backslash {
591 continuing = true;
592 } else {
593 continuing = false;
594 if !cur_text.is_empty() {
595 result.push(LogicalLine {
596 line: cur_line,
597 indent: cur_indent,
598 text: std::mem::take(&mut cur_text),
599 });
600 }
601 }
602 }
603
604 if continuing && !cur_text.is_empty() {
605 result.push(LogicalLine {
606 line: cur_line,
607 indent: cur_indent,
608 text: cur_text,
609 });
610 }
611
612 result
613}
614
615fn split_top_level(s: &str, delim: char) -> Vec<&str> {
616 let mut parts = Vec::new();
617 let mut depth: usize = 0;
618 let mut start = 0;
619 for (idx, ch) in s.char_indices() {
620 match ch {
621 '(' | '[' | '{' => depth += 1,
622 ')' | ']' | '}' => depth = depth.saturating_sub(1),
623 c if c == delim && depth == 0 => {
624 parts.push(&s[start..idx]);
625 start = idx + ch.len_utf8();
626 }
627 _ => {}
628 }
629 }
630 parts.push(&s[start..]);
631 parts
632}
633
634fn find_top_level_char(s: &str, target: char) -> Option<usize> {
635 let mut depth: usize = 0;
636 for (idx, ch) in s.char_indices() {
637 match ch {
638 '(' | '[' | '{' => depth += 1,
639 ')' | ']' | '}' => depth = depth.saturating_sub(1),
640 c if c == target && depth == 0 => return Some(idx),
641 _ => {}
642 }
643 }
644 None
645}
646
647fn parse_imports(lines: &[LogicalLine]) -> Vec<ParsedImport> {
648 let mut out = Vec::new();
649 for logical in lines {
650 for part in split_top_level(&logical.text, ';') {
651 let stmt = part.trim();
652 if stmt.is_empty() {
653 continue;
654 }
655 if stmt.starts_with("import") {
656 out.extend(parse_plain_import_stmt(stmt, logical.line));
657 } else if stmt.starts_with("from") {
658 if let Some(parsed) = parse_from_import_stmt(stmt, logical.line) {
659 out.push(parsed);
660 }
661 }
662 }
663 }
664 out
665}
666
667fn parse_plain_import_stmt(stmt: &str, line: u32) -> Vec<ParsedImport> {
668 let Some(rest) = stmt.strip_prefix("import") else {
669 return Vec::new();
670 };
671 if !rest.chars().next().is_some_and(|c| c.is_ascii_whitespace()) {
672 return Vec::new();
673 }
674 let mut out = Vec::new();
675 for item in rest.split(',') {
676 let item = item.trim();
677 if item.is_empty() {
678 continue;
679 }
680 let tokens: Vec<&str> = item.split_whitespace().collect();
681 match tokens.as_slice() {
682 [module] if is_valid_dotted_name(module) => {
683 out.push(ParsedImport::Import {
684 line,
685 module: (*module).to_string(),
686 alias: (*module).to_string(),
687 });
688 }
689 [module, "as", alias] if is_valid_dotted_name(module) && is_valid_ident(alias) => {
690 out.push(ParsedImport::Import {
691 line,
692 module: (*module).to_string(),
693 alias: (*alias).to_string(),
694 });
695 }
696 _ => {}
697 }
698 }
699 out
700}
701
702fn parse_from_import_stmt(stmt: &str, line: u32) -> Option<ParsedImport> {
703 let rest = stmt.strip_prefix("from")?;
704 let first = rest.chars().next()?;
705 if !first.is_ascii_whitespace() && first != '.' {
706 return None;
707 }
708 let rest = rest.trim_start();
709 let dots = rest.bytes().take_while(|&b| b == b'.').count();
710 let after_dots = &rest[dots..];
711
712 let (module, after_import) = if dots > 0 {
713 if after_dots.is_empty() {
714 return None;
715 }
716 if after_dots
717 .chars()
718 .next()
719 .is_some_and(|c| c.is_ascii_whitespace())
720 {
721 (
722 String::new(),
723 strip_import_keyword(after_dots.trim_start())?,
724 )
725 } else if let Some(after_kw) = strip_import_keyword(after_dots) {
726 (String::new(), after_kw)
727 } else {
728 let mod_end = after_dots
729 .find(|c: char| c.is_ascii_whitespace())
730 .unwrap_or(after_dots.len());
731 let mod_part = &after_dots[..mod_end];
732 if !is_valid_dotted_name(mod_part) {
733 return None;
734 }
735 let remainder = after_dots[mod_end..].trim_start();
736 (mod_part.to_string(), strip_import_keyword(remainder)?)
737 }
738 } else {
739 let mod_end = after_dots
740 .find(|c: char| c.is_ascii_whitespace())
741 .unwrap_or(after_dots.len());
742 let mod_part = &after_dots[..mod_end];
743 if mod_part == "import" || !is_valid_dotted_name(mod_part) {
744 return None;
745 }
746 let remainder = after_dots[mod_end..].trim_start();
747 (mod_part.to_string(), strip_import_keyword(remainder)?)
748 };
749
750 let mut list_text = after_import.trim();
751 if let Some(inner) = list_text
752 .strip_prefix('(')
753 .and_then(|s| s.strip_suffix(')'))
754 {
755 list_text = inner.trim();
756 }
757
758 let mut items = Vec::new();
759 for piece in list_text.split(',') {
760 let piece = piece.trim();
761 if piece.is_empty() {
762 continue;
763 }
764 if piece == "*" {
765 items.push(FromItem::Wildcard);
766 continue;
767 }
768 let tokens: Vec<&str> = piece.split_whitespace().collect();
769 match tokens.as_slice() {
770 [name] if is_valid_ident(name) => {
771 items.push(FromItem::Name {
772 orig: (*name).to_string(),
773 local: (*name).to_string(),
774 });
775 }
776 [name, "as", alias] if is_valid_ident(name) && is_valid_ident(alias) => {
777 items.push(FromItem::Name {
778 orig: (*name).to_string(),
779 local: (*alias).to_string(),
780 });
781 }
782 _ => {}
783 }
784 }
785
786 if items.is_empty() {
787 return None;
788 }
789
790 Some(ParsedImport::From {
791 line,
792 dots,
793 module,
794 items,
795 })
796}
797
798fn strip_import_keyword(s: &str) -> Option<&str> {
799 let rest = s.strip_prefix("import")?;
800 let next = rest.chars().next()?;
801 if next.is_ascii_whitespace() || next == '(' || next == '*' {
802 Some(rest.trim())
803 } else {
804 None
805 }
806}
807
808fn resolve_plain_import(
809 module: &str,
810 package_segs: &[String],
811 unit_set: &HashSet<String>,
812) -> Option<String> {
813 let segs: Vec<&str> = module.split('.').collect();
814 if let Some(found) = longest_prefix_match(&segs, 1, unit_set) {
815 return Some(found);
816 }
817 if !package_segs.is_empty() {
818 let mut combined: Vec<&str> = package_segs.iter().map(|s| s.as_str()).collect();
819 combined.extend(segs);
820 if let Some(found) = longest_prefix_match(&combined, package_segs.len() + 1, unit_set) {
821 return Some(found);
822 }
823 }
824 None
825}
826
827fn longest_prefix_match(
828 segs: &[&str],
829 min_len: usize,
830 unit_set: &HashSet<String>,
831) -> Option<String> {
832 if segs.len() < min_len {
833 return None;
834 }
835 for len in (min_len..=segs.len()).rev() {
836 let candidate = segs[..len].join(".");
837 if unit_set.contains(&candidate) {
838 return Some(candidate);
839 }
840 }
841 None
842}
843
844#[allow(clippy::too_many_arguments)]
845fn resolve_from_import(
846 info: &PyUnitInfo,
847 line: u32,
848 dots: usize,
849 module: &str,
850 items: &[FromItem],
851 unit_set: &HashSet<String>,
852 top_level_names: &HashSet<String>,
853 unit_to_group: &HashMap<String, String>,
854 edges: &mut Vec<Edge>,
855 unresolved: &mut Vec<Unresolved>,
856 direct_from_names: &mut Vec<(String, String)>,
857 module_aliases: &mut Vec<(String, String)>,
858 init_reexports: &mut HashMap<(String, String), Vec<(String, String)>>,
859) {
860 let written = format!("{}{}", ".".repeat(dots), module);
861
862 if dots > 0 {
863 let up = dots - 1;
864 if up > info.package_segs.len() {
865 unresolved.push(Unresolved {
866 file: info.file_rel.clone(),
867 line,
868 reference: written,
869 });
870 return;
871 }
872 let mut base_segs: Vec<String> = info.package_segs[..info.package_segs.len() - up].to_vec();
873 if !module.is_empty() {
874 base_segs.extend(module.split('.').map(|s| s.to_string()));
875 }
876 let base_mod = base_segs.join(".");
877 let mut any_unresolved = false;
878
879 for item in items {
880 match item {
881 FromItem::Wildcard => {
882 if !base_mod.is_empty() && unit_set.contains(&base_mod) {
883 emit_edges(&info.id, &base_mod, unit_to_group, edges);
884 } else {
885 any_unresolved = true;
886 }
887 }
888 FromItem::Name { orig, local } => {
889 let sub_candidate = if base_mod.is_empty() {
890 orig.clone()
891 } else {
892 format!("{base_mod}.{orig}")
893 };
894 if unit_set.contains(&sub_candidate) {
895 emit_edges(&info.id, &sub_candidate, unit_to_group, edges);
896 module_aliases.push((sub_candidate, local.clone()));
897 } else if !base_mod.is_empty() && unit_set.contains(&base_mod) {
898 emit_edges(&info.id, &base_mod, unit_to_group, edges);
899 direct_from_names.push((base_mod.clone(), orig.clone()));
900 if info.is_init {
901 init_reexports
902 .entry((info.id.clone(), local.clone()))
903 .or_default()
904 .push((base_mod.clone(), orig.clone()));
905 }
906 } else {
907 any_unresolved = true;
908 }
909 }
910 }
911 }
912
913 if any_unresolved {
914 unresolved.push(Unresolved {
915 file: info.file_rel.clone(),
916 line,
917 reference: written,
918 });
919 }
920 return;
921 }
922
923 let mut any_unresolved = false;
924 for item in items {
925 match item {
926 FromItem::Wildcard => {
927 if unit_set.contains(module) {
928 emit_edges(&info.id, module, unit_to_group, edges);
929 } else if let Some(local_mod) = prefixed_unit(&info.package_segs, module, unit_set)
930 {
931 emit_edges(&info.id, &local_mod, unit_to_group, edges);
932 } else if first_segment_in(module, top_level_names) {
933 any_unresolved = true;
934 }
935 }
936 FromItem::Name { orig, local } => {
937 let root_sub = format!("{module}.{orig}");
938 if unit_set.contains(&root_sub) {
939 emit_edges(&info.id, &root_sub, unit_to_group, edges);
940 module_aliases.push((root_sub, local.clone()));
941 continue;
942 }
943 if unit_set.contains(module) {
944 emit_edges(&info.id, module, unit_to_group, edges);
945 direct_from_names.push((module.to_string(), orig.clone()));
946 if info.is_init {
947 init_reexports
948 .entry((info.id.clone(), local.clone()))
949 .or_default()
950 .push((module.to_string(), orig.clone()));
951 }
952 continue;
953 }
954 if !info.package_segs.is_empty() {
955 let pkg_prefix = info.package_segs.join(".");
956 let local_sub = format!("{pkg_prefix}.{module}.{orig}");
957 if unit_set.contains(&local_sub) {
958 emit_edges(&info.id, &local_sub, unit_to_group, edges);
959 module_aliases.push((local_sub, local.clone()));
960 continue;
961 }
962 let local_mod = format!("{pkg_prefix}.{module}");
963 if unit_set.contains(&local_mod) {
964 emit_edges(&info.id, &local_mod, unit_to_group, edges);
965 direct_from_names.push((local_mod.clone(), orig.clone()));
966 if info.is_init {
967 init_reexports
968 .entry((info.id.clone(), local.clone()))
969 .or_default()
970 .push((local_mod, orig.clone()));
971 }
972 continue;
973 }
974 }
975 if first_segment_in(module, top_level_names) {
976 any_unresolved = true;
977 }
978 }
979 }
980 }
981
982 if any_unresolved {
983 unresolved.push(Unresolved {
984 file: info.file_rel.clone(),
985 line,
986 reference: written,
987 });
988 }
989}
990
991fn prefixed_unit(
992 package_segs: &[String],
993 module: &str,
994 unit_set: &HashSet<String>,
995) -> Option<String> {
996 if package_segs.is_empty() {
997 return None;
998 }
999 let candidate = format!("{}.{module}", package_segs.join("."));
1000 unit_set.contains(&candidate).then_some(candidate)
1001}
1002
1003fn first_segment_in(module: &str, top_level_names: &HashSet<String>) -> bool {
1004 module
1005 .split('.')
1006 .next()
1007 .is_some_and(|first| top_level_names.contains(first))
1008}
1009
1010fn emit_edges(
1011 from_unit: &str,
1012 to_unit: &str,
1013 unit_to_group: &HashMap<String, String>,
1014 edges: &mut Vec<Edge>,
1015) {
1016 if from_unit == to_unit {
1017 return;
1018 }
1019 edges.push(Edge {
1020 from: from_unit.to_string(),
1021 to: to_unit.to_string(),
1022 level: "unit".to_string(),
1023 });
1024 if let (Some(from_group), Some(to_group)) =
1025 (unit_to_group.get(from_unit), unit_to_group.get(to_unit))
1026 {
1027 if from_group != to_group {
1028 edges.push(Edge {
1029 from: from_group.clone(),
1030 to: to_group.clone(),
1031 level: "group".to_string(),
1032 });
1033 }
1034 }
1035}
1036
1037fn extract_structures(lines: &[LogicalLine], unit_id: &str, file_rel: &str) -> Vec<Structure> {
1038 let mut structures = Vec::new();
1039 let mut pending_decorators: Vec<&str> = Vec::new();
1040
1041 for (idx, logical) in lines.iter().enumerate() {
1042 if logical.indent != 0 {
1043 continue;
1044 }
1045 let text = logical.text.as_str();
1046 if text.starts_with('@') {
1047 pending_decorators.push(text);
1048 continue;
1049 }
1050
1051 if let Some((class_name, bases)) = parse_class_header(text) {
1052 let kind = classify_structure(&pending_decorators, &bases);
1053 pending_decorators.clear();
1054
1055 if let Some(kind) = kind {
1056 let fields = extract_class_fields(&lines[idx + 1..]);
1057 structures.push(Structure {
1058 id: format!("{unit_id}.{class_name}"),
1059 name: class_name,
1060 kind: kind.to_string(),
1061 unit: unit_id.to_string(),
1062 file: file_rel.to_string(),
1063 line: logical.line,
1064 serialisable: true,
1065 fields,
1066 referenced_by: Vec::new(),
1067 });
1068 }
1069 } else {
1070 pending_decorators.clear();
1071 }
1072 }
1073
1074 structures
1075}
1076
1077fn parse_class_header(text: &str) -> Option<(String, Vec<String>)> {
1078 let rest = text.strip_prefix("class")?;
1079 if !rest.chars().next().is_some_and(|c| c.is_ascii_whitespace()) {
1080 return None;
1081 }
1082 let rest = rest.trim_start();
1083 let colon_idx = find_top_level_char(rest, ':')?;
1084 let header = rest[..colon_idx].trim();
1085
1086 if let Some(open_paren) = header.find('(') {
1087 let name = header[..open_paren].trim();
1088 if !is_valid_ident(name) {
1089 return None;
1090 }
1091 let close_paren = header.rfind(')')?;
1092 if close_paren <= open_paren {
1093 return None;
1094 }
1095 let bases_str = &header[open_paren + 1..close_paren];
1096 let bases = split_top_level(bases_str, ',')
1097 .into_iter()
1098 .filter_map(|b| parse_base_last_name(b.trim()))
1099 .collect();
1100 Some((name.to_string(), bases))
1101 } else {
1102 if !is_valid_ident(header) {
1103 return None;
1104 }
1105 Some((header.to_string(), Vec::new()))
1106 }
1107}
1108
1109fn parse_base_last_name(base: &str) -> Option<String> {
1110 if base.is_empty() || find_top_level_char(base, '=').is_some() {
1111 return None;
1112 }
1113 let without_generic = base.split('[').next().unwrap_or(base).trim();
1114 let last = without_generic.split('.').next_back()?.trim();
1115 if is_valid_ident(last) {
1116 Some(last.to_string())
1117 } else {
1118 None
1119 }
1120}
1121
1122fn classify_structure(decorators: &[&str], bases: &[String]) -> Option<&'static str> {
1123 if decorators.iter().any(|d| is_dataclass_decorator(d)) {
1124 return Some("dataclass");
1125 }
1126 if bases.iter().any(|b| b == "BaseModel") {
1127 return Some("model");
1128 }
1129 if bases.iter().any(|b| b == "TypedDict") {
1130 return Some("typeddict");
1131 }
1132 None
1133}
1134
1135fn is_dataclass_decorator(decorator: &str) -> bool {
1136 let Some(rest) = decorator.strip_prefix('@') else {
1137 return false;
1138 };
1139 let rest = rest.trim();
1140 let name_part = match rest.find('(') {
1141 Some(pos) => {
1142 if !rest.ends_with(')') {
1143 return false;
1144 }
1145 rest[..pos].trim()
1146 }
1147 None => rest,
1148 };
1149 name_part == "dataclass" || name_part == "dataclasses.dataclass"
1150}
1151
1152fn extract_class_fields(body_lines: &[LogicalLine]) -> Vec<Field> {
1153 let mut fields = Vec::new();
1154 let mut body_indent: Option<usize> = None;
1155
1156 for line in body_lines {
1157 if line.indent == 0 {
1158 break;
1159 }
1160 let target_indent = *body_indent.get_or_insert(line.indent);
1161 if line.indent != target_indent {
1162 continue;
1163 }
1164 if let Some(field) = parse_field_line(&line.text) {
1165 fields.push(field);
1166 }
1167 }
1168
1169 fields
1170}
1171
1172fn parse_field_line(text: &str) -> Option<Field> {
1173 let colon_idx = text.find(':')?;
1174 let name = text[..colon_idx].trim();
1175 if !is_valid_ident(name) || PYTHON_KEYWORDS.contains(&name) {
1176 return None;
1177 }
1178 let rhs = &text[colon_idx + 1..];
1179 if rhs.starts_with('=') {
1180 return None;
1181 }
1182 let type_part = match find_top_level_char(rhs, '=') {
1183 Some(eq_idx) => rhs[..eq_idx].trim(),
1184 None => rhs.trim(),
1185 };
1186 if type_part.is_empty() || is_classvar_type(type_part) {
1187 return None;
1188 }
1189 Some(Field {
1190 name: name.to_string(),
1191 ty: type_part.to_string(),
1192 })
1193}
1194
1195fn is_classvar_type(ty: &str) -> bool {
1196 let base = ty.split('[').next().unwrap_or(ty).trim();
1197 let last = base.split('.').next_back().unwrap_or("").trim();
1198 last == "ClassVar"
1199}
1200
1201fn code_contains_attr_ref(code: &str, alias: &str, struct_name: &str) -> bool {
1202 let needle = format!("{alias}.{struct_name}");
1203 let mut offset = 0;
1204 while let Some(pos) = code[offset..].find(&needle) {
1205 let start = offset + pos;
1206 let end = start + needle.len();
1207 let before_ok = if start == 0 {
1208 true
1209 } else {
1210 let prev = code[..start].chars().next_back().unwrap();
1211 !is_ident_continue(prev) && prev != '.'
1212 };
1213 let after_ok = if end == code.len() {
1214 true
1215 } else {
1216 let next = code[end..].chars().next().unwrap();
1217 !is_ident_continue(next)
1218 };
1219 if before_ok && after_ok {
1220 return true;
1221 }
1222 offset = start + 1;
1223 while offset < code.len() && !code.is_char_boundary(offset) {
1224 offset += 1;
1225 }
1226 }
1227 false
1228}
1229
1230fn is_valid_dotted_name(s: &str) -> bool {
1231 !s.is_empty() && s.split('.').all(is_valid_ident)
1232}
1233
1234fn is_valid_ident(s: &str) -> bool {
1235 let mut chars = s.chars();
1236 let Some(first) = chars.next() else {
1237 return false;
1238 };
1239 is_ident_start(first) && chars.all(is_ident_continue)
1240}
1241
1242fn is_ident_start(c: char) -> bool {
1243 c == '_' || c.is_alphabetic()
1244}
1245
1246fn is_ident_continue(c: char) -> bool {
1247 c == '_' || c.is_alphanumeric()
1248}