zoning 1.4.0

An import-topology gate: declare the zones a package's imports may cross, and judge the real import graph against them.
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
//! Python — the second dialect, and the one whose imports are not paths.
//!
//! Every other property this tool needs falls out of one difference from Zig:
//! `@import("../a/b.zig")` already spells the file to open, but `import a.b` and
//! `from . import c` spell a *module name* — dotted, sometimes anchored to the
//! importing file by a run of leading dots, resolved against `sys.path` by an
//! algorithm this tool does not run. So this dialect's whole job is arithmetic
//! that [`super::resolve`] never has to see: turn a dotted or dot-relative spelling
//! into the same `../`-collapsed path a Zig import would have written, using only
//! the importing file's own depth and the set of top-level names the survey already
//! knows are local — never a filesystem probe, and never PYTHONPATH.
//!
//! A dotted or absolute spelling is ambiguous in one more way a path is not: `x.py`
//! and `x/__init__.py` are both legal answers to "the file named `x`", and nothing
//! in the import statement says which. Both are offered as candidates; at most one
//! can exist in a real tree, and [`super::resolve`]'s caller already drops whichever
//! one is not a judged file, so an author never sees the ambiguity.

use super::dialect::{Dialect, Import};
use super::prose::Prose;

/// The Python dialect.
pub(super) struct Python;

// TOML and Python happen to agree on prose: `#` to end of line, `"`/`'` single-line
// literals, `"""`/`'''` literals that may hold a raw newline. One table serves both
// `.py` source and `pyproject.toml`. They agree on the join too — TOML spells one only
// inside a multi-line string, which is blanked whole before a backslash is ever read.
const PROSE: Prose = Prose {
    line_comment: "#",
    block_comment: None,
    line_string: None,
    quotes: b"\"'",
    triple_quotes: &["\"\"\"", "'''"],
    line_join: true,
};

impl Dialect for Python {
    fn name(&self) -> &'static str {
        "python"
    }

    fn extensions(&self) -> &'static [&'static str] {
        &["py"]
    }

    fn manifests(&self) -> &'static [&'static str] {
        &["pyproject.toml", "setup.py", "setup.cfg"]
    }

    // `path = "…"` is how every tool that admits an in-tree dependency spells it —
    // uv and Poetry both write it as a key inside an inline table under
    // `[tool.*.sources]`/`[tool.*.dependencies]`. The key alone recovers it without a
    // TOML parser, same trade Zig's `.path` search makes: a stray match only ever
    // excuses a directory the manifest already pointed at.
    fn vendored(&self, manifest: &str) -> Vec<String> {
        let code = PROSE.code_only(manifest);
        let raw = manifest.as_bytes();
        let mut out = Vec::new();
        let mut i = 0;
        while let Some(head) = find_word(&code, b"path", i) {
            let mut j = head + 4;
            while matches!(code.get(j), Some(b' ' | b'\t')) {
                j += 1;
            }
            i = head + 1;
            if code.get(j) != Some(&b'=') {
                continue;
            }
            if let Some(dir) = literal(raw, j + 1) {
                out.push(dir.trim_end_matches('/').to_owned());
            }
        }
        out
    }

    // `name` under the standard `[project]` table (PEP 621). `setup.py`/`setup.cfg`
    // name a package no more uniformly than they format the rest of themselves, so
    // this reads only the one manifest shape that actually declares it in one place.
    fn declared(&self, manifest: &str) -> Option<String> {
        let code = PROSE.code_only(manifest);
        let raw = manifest.as_bytes();
        let head = find_line(&code, b"[project]")?;
        let body_start = head + b"[project]".len();
        let body_end = find_next_table(&code, body_start);
        let mut i = body_start;
        while i < body_end {
            let line_end =
                code[i..body_end].iter().position(|&b| b == b'\n').map_or(body_end, |o| i + o);
            let indent =
                code[i..line_end].iter().take_while(|&&b| matches!(b, b' ' | b'\t')).count();
            let key = i + indent;
            if code[key..line_end].starts_with(b"name") {
                let mut j = key + 4;
                while matches!(code.get(j), Some(b' ' | b'\t')) {
                    j += 1;
                }
                if code.get(j) == Some(&b'=')
                    && let Some(value) = literal(raw, j + 1)
                {
                    return Some(value);
                }
            }
            i = line_end + 1;
        }
        None
    }

    // The union of `sys.stdlib_module_names` across every CPython from 3.10 (the
    // first release to expose the set at all) through 3.14, so a contract reads the
    // same regardless of which interpreter actually runs it. A name retired after
    // 3.9 or not yet added is still ambient here — over-including the standard
    // library costs nothing a contract would notice, where under-including it would
    // demand a `use` grant for `cgi` on one version and not another.
    fn ambient(&self) -> &'static [&'static str] {
        STDLIB
    }

    fn prose(&self) -> &Prose {
        &PROSE
    }

    fn imports(
        &self,
        path: &str,
        roots: &[&str],
        own: &str,
        _source: &str,
        code: &[u8],
    ) -> Vec<Import> {
        // Hyphen and underscore are the same package to a human, but only one of
        // them can appear in an identifier — a manifest's `my-package` is always
        // spelled `import my_package` in code, never with the hyphen.
        let own = own.replace('-', "_");
        let mut out = Vec::new();
        let mut i = 0;
        while i < code.len() {
            let from_at = find_word(code, b"from", i);
            let import_at = find_word(code, b"import", i);
            let Some(at) = min_of(from_at, import_at) else { break };
            if !at_statement_start(code, at) {
                i = at + 1;
                continue;
            }
            if from_at == Some(at) {
                let (found, end) = parse_from(code, roots, &own, path, at);
                out.extend(found);
                i = end;
            } else {
                let (found, end) = parse_plain(code, roots, &own, path, at);
                out.extend(found);
                i = end;
            }
        }
        out
    }

    // A local candidate is always spelled as a path this dialect itself produced in
    // `imports` — every other spec is the bare top-level name of a module the build
    // (or the standard library) resolves, never a path.
    #[allow(clippy::case_sensitive_file_extension_comparisons, reason = "import specs are literal")]
    fn is_local(&self, spec: &str) -> bool {
        spec.ends_with(".py")
    }

    fn escape_remedy(&self) -> &'static str {
        "Python cannot follow a relative import past the top of its own package; \
         name the dependency as an absolute import instead"
    }
}

/// `from <dots><module>? import <names>` — `at` is the byte offset of `from`.
/// Returns the imports it read and the offset just past the statement.
fn parse_from(
    code: &[u8],
    roots: &[&str],
    own: &str,
    path: &str,
    at: usize,
) -> (Vec<Import>, usize) {
    let mut j = at + 4;
    if !matches!(code.get(j), Some(b' ' | b'\t')) {
        return (Vec::new(), at + 4);
    }
    j = skip_h(code, j);
    let dots = code[j..].iter().take_while(|&&b| b == b'.').count();
    j += dots;
    let mod_start = j;
    j = skip_dotted(code, j);
    let mut module = std::str::from_utf8(&code[mod_start..j]).unwrap_or("");
    j = skip_h(code, j);
    let Some(k) = find_word(code, b"import", j) else { return (Vec::new(), at + 4) };
    if code[j..k].iter().any(|&b| !matches!(b, b' ' | b'\t' | b'\n')) {
        return (Vec::new(), at + 4); // `from` used elsewhere, e.g. `raise x from y`
    }
    j = skip_h(code, k + 6);
    let (names, end) = read_name_list(code, j);

    let mut out = Vec::new();
    if dots == 0 {
        if self_ref(module, roots, own) {
            // `from acme.contracts import X`, read from inside `acme` itself: the
            // leading segment names this package's own top level rather than a
            // subdirectory, so it contributes no path segment.
            module = strip_own(module, own);
        } else {
            let top = module.split('.').next().unwrap_or("");
            if top.is_empty() || !roots.contains(&top) {
                if !top.is_empty() {
                    out.push(spec(at, top.to_owned()));
                }
                return (out, end);
            }
        }
    }
    let climbs = if dots == 0 { depth_of(path) } else { dots - 1 };
    let prefix = "../".repeat(climbs);
    let dir = if module.is_empty() {
        prefix.trim_end_matches('/').to_owned()
    } else {
        format!("{prefix}{}", module.replace('.', "/"))
    };
    if dots == 0 {
        out.extend(ancestors(&prefix, module, path).into_iter().map(|found| spec(at, found)));
    }
    if !module.is_empty() {
        out.push(spec(at, format!("{dir}.py")));
    }
    out.push(spec(at, format!("{dir}/__init__.py")));
    for name in names {
        if name == "*" {
            continue;
        }
        out.push(spec(at, format!("{dir}/{name}.py")));
        out.push(spec(at, format!("{dir}/{name}/__init__.py")));
    }
    (out, end)
}

/// `import <dotted>[ as alias][, <dotted>[ as alias]]*` — `at` is the byte offset of
/// `import`. Returns the imports it read and the offset just past the statement.
fn parse_plain(
    code: &[u8],
    roots: &[&str],
    own: &str,
    path: &str,
    at: usize,
) -> (Vec<Import>, usize) {
    let start = at + 6;
    let eol = code[start..]
        .iter()
        .position(|&b| b == b'\n' || b == b';')
        .map_or(code.len(), |o| start + o);
    let mut out = Vec::new();
    for piece in code[start..eol].split(|&b| b == b',') {
        let piece = trim(piece);
        if piece.is_empty() {
            continue;
        }
        let cut = find(piece, b" as ").unwrap_or(piece.len());
        let Ok(dotted) = std::str::from_utf8(trim(&piece[..cut])) else { continue };
        if dotted.is_empty() {
            continue;
        }
        let dotted = if self_ref(dotted, roots, own) {
            strip_own(dotted, own) // `import acme.contracts`, from inside `acme`
        } else {
            let top = dotted.split('.').next().unwrap_or("");
            if !roots.contains(&top) {
                out.push(spec(at, top.to_owned()));
                continue;
            }
            dotted
        };
        let prefix = "../".repeat(depth_of(path));
        let dir = if dotted.is_empty() {
            prefix.trim_end_matches('/').to_owned()
        } else {
            format!("{prefix}{}", dotted.replace('.', "/"))
        };
        out.extend(ancestors(&prefix, dotted, path).into_iter().map(|found| spec(at, found)));
        if !dotted.is_empty() {
            out.push(spec(at, format!("{dir}.py")));
        }
        out.push(spec(at, format!("{dir}/__init__.py")));
    }
    (out, eol)
}

/// Every ancestor package a dotted spelling initializes that `path` had not already.
///
/// `import a.b.c` binds one name and initializes three packages: the interpreter executes
/// `a/__init__.py`, then `a/b/__init__.py`, then the leaf, in that order. So a file
/// reaching for a leaf has genuinely taken on whatever its ancestors import — and where a
/// contract puts an ancestor's `__init__.py` above the importer, that is an up-import the
/// leaf's own path cannot show. Reading only the leaf lets a stack no interpreter could
/// honour pass clean.
///
/// Only the ancestors the importer is not *already* inside, which is the same reason a
/// relative import contributes none at all: reaching `a.b.c` from within `a/` cannot be a
/// new dependency on `a/__init__.py`, because nothing in `a/` runs until it has. Counting
/// those would make the ordinary absolute self-import — `from mypkg.sub import x`, written
/// inside `mypkg`, with any non-empty `__init__.py` — a cycle through the package root in
/// every Python package alive.
///
/// `module` is dotted and absolute; `prefix` is the `../` climb to the module root, so
/// each name walked is module-root-relative and comparable to `path` directly.
fn ancestors(prefix: &str, module: &str, path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut walked = String::new();
    let mut segments = module.split('.').peekable();
    // The last segment is the module itself, which the caller emits with both of its
    // candidate spellings; only the packages above it are this function's business.
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            break;
        }
        if !walked.is_empty() {
            walked.push('/');
        }
        walked.push_str(segment);
        if !path.starts_with(&format!("{walked}/")) {
            out.push(format!("{prefix}{walked}/__init__.py"));
        }
    }
    out
}

/// Does `module` (an absolute, dot-free-leading spelling) name this package's own
/// top level rather than a subdirectory `roots` already knows about?
///
/// Guarded by `!roots.contains(&own)` so a package that genuinely has a
/// subdirectory of its own name — the ordinary nested layout — keeps taking the
/// path `roots` already resolves correctly; this only fires for the flat layout
/// `roots` cannot see into, where the package's declared name has no directory of
/// its own to be.
fn self_ref(module: &str, roots: &[&str], own: &str) -> bool {
    !own.is_empty()
        && !roots.contains(&own)
        && (module == own || module.strip_prefix(own).is_some_and(|rest| rest.starts_with('.')))
}

/// `module` with its leading `own` (and the dot after it, if any) removed.
fn strip_own<'a>(module: &'a str, own: &str) -> &'a str {
    module.get(own.len()..).unwrap_or("").trim_start_matches('.')
}

fn spec(offset: usize, spec: String) -> Import {
    Import { offset, spec }
}

/// How many directories separate `path` from the module root.
fn depth_of(path: &str) -> usize {
    path.rsplit_once('/').map_or(0, |(dir, _)| dir.split('/').count())
}

/// Byte offset of whichever of two candidate positions is earlier.
fn min_of(a: Option<usize>, b: Option<usize>) -> Option<usize> {
    match (a, b) {
        (Some(x), Some(y)) => Some(x.min(y)),
        (Some(x), None) | (None, Some(x)) => Some(x),
        (None, None) => None,
    }
}

/// Is the byte at `i`, after only horizontal whitespace, the start of a statement?
fn at_statement_start(code: &[u8], i: usize) -> bool {
    let mut j = i;
    while j > 0 && matches!(code[j - 1], b' ' | b'\t') {
        j -= 1;
    }
    j == 0 || matches!(code[j - 1], b'\n' | b';' | b':')
}

fn is_ident(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80
}

/// Next word-bounded occurrence of `word` at or after `from`.
fn find_word(code: &[u8], word: &[u8], from: usize) -> Option<usize> {
    let mut i = from;
    while let Some(k) = find(&code[i..], word) {
        let at = i + k;
        let before = at == 0 || !is_ident(code[at - 1]);
        let after = code.get(at + word.len()).is_none_or(|&b| !is_ident(b));
        if before && after {
            return Some(at);
        }
        i = at + 1;
    }
    None
}

/// Skip spaces and tabs only — never a newline, since a bare header token never
/// legitimately continues onto the next line without parens or a backslash.
fn skip_h(code: &[u8], mut j: usize) -> usize {
    while matches!(code.get(j), Some(b' ' | b'\t')) {
        j += 1;
    }
    j
}

/// Skip an `identifier(.identifier)*` run, approximating PEP 3131: any byte ≥ 0x80 is
/// assumed to continue a Unicode identifier rather than lexing one exactly.
fn skip_dotted(code: &[u8], mut j: usize) -> usize {
    while code
        .get(j)
        .is_some_and(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.') || b >= 0x80)
    {
        j += 1;
    }
    j
}

/// The `import` clause's name list: parenthesized (may span lines) or a bare
/// comma list running to end of line. Returns the names and the offset just past.
fn read_name_list(code: &[u8], j: usize) -> (Vec<String>, usize) {
    if code.get(j) == Some(&b'(') {
        let close = find(&code[j + 1..], b")").map_or(code.len(), |o| j + 1 + o);
        (split_names(&code[j + 1..close]), (close + 1).min(code.len()))
    } else {
        let eol =
            code[j..].iter().position(|&b| b == b'\n' || b == b';').map_or(code.len(), |o| j + o);
        (split_names(&code[j..eol]), eol)
    }
}

fn split_names(chunk: &[u8]) -> Vec<String> {
    chunk
        .split(|&b| b == b',')
        .filter_map(|raw| {
            let piece = trim(raw);
            if piece.is_empty() {
                None
            } else if piece == b"*" {
                Some("*".to_owned())
            } else {
                let cut = find(piece, b" as ").unwrap_or(piece.len());
                std::str::from_utf8(trim(&piece[..cut]))
                    .ok()
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned)
            }
        })
        .collect()
}

fn trim(bytes: &[u8]) -> &[u8] {
    let start = bytes.iter().position(|&b| !b.is_ascii_whitespace()).unwrap_or(bytes.len());
    let end = bytes.iter().rposition(|&b| !b.is_ascii_whitespace()).map_or(start, |p| p + 1);
    &bytes[start..end]
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|w| w == needle)
}

/// Byte offset of a line whose entire trimmed content is exactly `needle`.
fn find_line(code: &[u8], needle: &[u8]) -> Option<usize> {
    let mut i = 0;
    while i < code.len() {
        let end = code[i..].iter().position(|&b| b == b'\n').map_or(code.len(), |o| i + o);
        if trim(&code[i..end]) == needle {
            return Some(i);
        }
        i = end + 1;
    }
    None
}

/// The next line starting with `[` at or after `from`, or the end of the buffer —
/// the boundary of the table `from` sits inside.
fn find_next_table(code: &[u8], from: usize) -> usize {
    let mut i = from;
    while i < code.len() {
        let end = code[i..].iter().position(|&b| b == b'\n').map_or(code.len(), |o| i + o);
        if trim(&code[i..end]).first() == Some(&b'[') {
            return i;
        }
        i = end + 1;
    }
    code.len()
}

/// Read the TOML string literal opening at or after `from` — basic (`"…"`, with
/// backslash escapes) or literal (`'…'`, without).
fn literal(raw: &[u8], from: usize) -> Option<String> {
    let mut i = from;
    while raw.get(i).is_some_and(u8::is_ascii_whitespace) {
        i += 1;
    }
    let quote = *raw.get(i)?;
    if quote != b'"' && quote != b'\'' {
        return None;
    }
    i += 1;
    let mut out = Vec::new();
    while let Some(&ch) = raw.get(i) {
        match ch {
            b'\\' if quote == b'"' && i + 1 < raw.len() => {
                out.push(raw[i + 1]);
                i += 2;
            }
            b'\n' => return None,
            b if b == quote => return String::from_utf8(out).ok(),
            _ => {
                out.push(ch);
                i += 1;
            }
        }
    }
    None
}

/// The union of `sys.stdlib_module_names` across `CPython` 3.10 through 3.14.
#[rustfmt::skip]
const STDLIB: &[&str] = &[
    "__future__", "_abc", "_aix_support", "_android_support", "_apple_support", "_ast",
    "_ast_unparse", "_asyncio", "_bisect", "_blake2", "_bootsubprocess", "_bz2", "_codecs",
    "_codecs_cn", "_codecs_hk", "_codecs_iso2022", "_codecs_jp", "_codecs_kr", "_codecs_tw",
    "_collections", "_collections_abc", "_colorize", "_compat_pickle", "_compression",
    "_contextvars", "_crypt", "_csv", "_ctypes", "_curses", "_curses_panel", "_datetime",
    "_dbm", "_decimal", "_elementtree", "_frozen_importlib", "_frozen_importlib_external",
    "_functools", "_gdbm", "_hashlib", "_heapq", "_hmac", "_imp", "_interpchannels",
    "_interpqueues", "_interpreters", "_io", "_ios_support", "_json", "_locale", "_lsprof",
    "_lzma", "_markupbase", "_md5", "_msi", "_multibytecodec", "_multiprocessing", "_opcode",
    "_opcode_metadata", "_operator", "_osx_support", "_overlapped", "_pickle", "_posixshmem",
    "_posixsubprocess", "_py_abc", "_py_warnings", "_pydatetime", "_pydecimal", "_pyio",
    "_pylong", "_pyrepl", "_queue", "_random", "_remote_debugging", "_scproxy", "_sha1",
    "_sha2", "_sha256", "_sha3", "_sha512", "_signal", "_sitebuiltins", "_socket", "_sqlite3",
    "_sre", "_ssl", "_stat", "_statistics", "_string", "_strptime", "_struct", "_suggestions",
    "_symtable", "_sysconfig", "_thread", "_threading_local", "_tkinter", "_tokenize",
    "_tracemalloc", "_types", "_typing", "_uuid", "_warnings", "_weakref", "_weakrefset",
    "_winapi", "_wmi", "_zoneinfo", "_zstd", "abc", "aifc", "annotationlib", "antigravity",
    "argparse", "array", "ast", "asynchat", "asyncio", "asyncore", "atexit", "audioop",
    "base64", "bdb", "binascii", "binhex", "bisect", "builtins", "bz2", "cProfile", "calendar",
    "cgi", "cgitb", "chunk", "cmath", "cmd", "code", "codecs", "codeop", "collections",
    "colorsys", "compileall", "compression", "concurrent", "configparser", "contextlib",
    "contextvars", "copy", "copyreg", "crypt", "csv", "ctypes", "curses", "dataclasses",
    "datetime", "dbm", "decimal", "difflib", "dis", "distutils", "doctest", "email",
    "encodings", "ensurepip", "enum", "errno", "faulthandler", "fcntl", "filecmp", "fileinput",
    "fnmatch", "fractions", "ftplib", "functools", "gc", "genericpath", "getopt", "getpass",
    "gettext", "glob", "graphlib", "grp", "gzip", "hashlib", "heapq", "hmac", "html", "http",
    "idlelib", "imaplib", "imghdr", "imp", "importlib", "inspect", "io", "ipaddress",
    "itertools", "json", "keyword", "lib2to3", "linecache", "locale", "logging", "lzma",
    "mailbox", "mailcap", "marshal", "math", "mimetypes", "mmap", "modulefinder", "msilib",
    "msvcrt", "multiprocessing", "netrc", "nis", "nntplib", "nt", "ntpath", "nturl2path",
    "numbers", "opcode", "operator", "optparse", "os", "ossaudiodev", "pathlib", "pdb",
    "pickle", "pickletools", "pipes", "pkgutil", "platform", "plistlib", "poplib", "posix",
    "posixpath", "pprint", "profile", "pstats", "pty", "pwd", "py_compile", "pyclbr", "pydoc",
    "pydoc_data", "pyexpat", "queue", "quopri", "random", "re", "readline", "reprlib",
    "resource", "rlcompleter", "runpy", "sched", "secrets", "select", "selectors", "shelve",
    "shlex", "shutil", "signal", "site", "smtpd", "smtplib", "sndhdr", "socket",
    "socketserver", "spwd", "sqlite3", "sre_compile", "sre_constants", "sre_parse", "ssl",
    "stat", "statistics", "string", "stringprep", "struct", "subprocess", "sunau", "symtable",
    "sys", "sysconfig", "syslog", "tabnanny", "tarfile", "telnetlib", "tempfile", "termios",
    "textwrap", "this", "threading", "time", "timeit", "tkinter", "token", "tokenize",
    "tomllib", "trace", "traceback", "tracemalloc", "tty", "turtle", "turtledemo", "types",
    "typing", "unicodedata", "unittest", "urllib", "uu", "uuid", "venv", "warnings", "wave",
    "weakref", "webbrowser", "winreg", "winsound", "wsgiref", "xdrlib", "xml", "xmlrpc",
    "zipapp", "zipfile", "zipimport", "zlib", "zoneinfo",
];

#[cfg(test)]
#[allow(clippy::expect_used, reason = "a test that cannot construct its fixture has failed")]
mod tests {
    use super::*;

    fn specs(path: &str, roots: &[&str], source: &str) -> Vec<String> {
        owned_specs(path, roots, "", source)
    }

    fn owned_specs(path: &str, roots: &[&str], own: &str, source: &str) -> Vec<String> {
        let code = PROSE.code_only(source);
        Python.imports(path, roots, own, source, &code).into_iter().map(|i| i.spec).collect()
    }

    #[test]
    fn plain_absolute_import_of_a_root_package() {
        assert_eq!(
            specs("pkg/mod.py", &["pkg"], "import pkg.util\n"),
            ["../pkg/util.py", "../pkg/util/__init__.py"]
        );
    }

    #[test]
    fn plain_import_of_an_external_dependency() {
        assert_eq!(specs("pkg/mod.py", &["pkg"], "import numpy as np\n"), ["numpy"]);
    }

    #[test]
    fn comma_separated_plain_imports() {
        // The importer is loose at the module root, so no climb is needed to reach a
        // sibling root package.
        assert_eq!(
            specs("mod.py", &["pkg"], "import os, pkg.a, sys\n"),
            ["os", "pkg/__init__.py", "pkg/a.py", "pkg/a/__init__.py", "sys"]
        );
    }

    #[test]
    fn from_import_of_named_submodules() {
        assert_eq!(
            specs("pkg/mod.py", &["pkg"], "from pkg import a, b\n"),
            [
                "../pkg.py",
                "../pkg/__init__.py",
                "../pkg/a.py",
                "../pkg/a/__init__.py",
                "../pkg/b.py",
                "../pkg/b/__init__.py",
            ]
        );
    }

    #[test]
    fn from_import_of_an_external_module_is_one_departure() {
        assert_eq!(
            specs("pkg/mod.py", &["pkg"], "from collections import OrderedDict\n"),
            ["collections"]
        );
    }

    #[test]
    fn relative_import_same_directory() {
        assert_eq!(
            specs("pkg/mod.py", &["pkg"], "from . import sibling\n"),
            ["/__init__.py", "/sibling.py", "/sibling/__init__.py"]
        );
    }

    #[test]
    fn relative_import_climbs_a_level() {
        assert_eq!(
            specs("pkg/sub/mod.py", &["pkg"], "from .. import sibling\n"),
            ["../__init__.py", "../sibling.py", "../sibling/__init__.py"]
        );
    }

    #[test]
    fn relative_import_with_a_named_module() {
        assert_eq!(
            specs("pkg/sub/mod.py", &["pkg"], "from ..util import helper\n"),
            [
                "../util.py",
                "../util/__init__.py",
                "../util/helper.py",
                "../util/helper/__init__.py",
            ]
        );
    }

    #[test]
    fn star_import_names_only_the_base() {
        assert_eq!(
            specs("pkg/mod.py", &["pkg"], "from pkg.sub import *\n"),
            ["../pkg/sub.py", "../pkg/sub/__init__.py"]
        );
    }

    #[test]
    fn parenthesized_multiline_names() {
        let src = "from pkg import (\n    a,\n    b as c,\n)\n";
        assert_eq!(
            specs("mod.py", &["pkg"], src),
            [
                "pkg.py",
                "pkg/__init__.py",
                "pkg/a.py",
                "pkg/a/__init__.py",
                "pkg/b.py",
                "pkg/b/__init__.py",
            ]
        );
    }

    #[test]
    fn comments_and_docstrings_are_not_mistaken_for_imports() {
        let src = "\
\"\"\"
import fake.one
\"\"\"
# import fake.two
import real\n";
        assert_eq!(specs("mod.py", &[], src), ["real"]);
    }

    // A flat-laid package — `root .`, no subdirectory shares its own name — whose
    // files nonetheless address their own top level the way an installed consumer
    // would: a package with no directory named after itself, where every one of
    // its own modules imports itself as `acme.contracts…`. Nothing in `roots` can
    // recognize that, since there is no `acme/` directory to have put there; this
    // is what `own` is for.
    #[test]
    fn a_flat_package_recognizes_its_own_declared_name() {
        assert_eq!(
            owned_specs(
                "runtime/host.py",
                &["contracts", "runtime"],
                "acme",
                "from acme.contracts.types import Event\n"
            ),
            [
                "../contracts/__init__.py",
                "../contracts/types.py",
                "../contracts/types/__init__.py",
                "../contracts/types/Event.py",
                "../contracts/types/Event/__init__.py",
            ]
        );
        assert_eq!(
            owned_specs(
                "runtime/host.py",
                &["contracts", "runtime"],
                "acme",
                "import acme.contracts.types\n"
            ),
            ["../contracts/__init__.py", "../contracts/types.py", "../contracts/types/__init__.py"]
        );
    }

    #[test]
    fn a_bare_self_import_names_the_module_roots_own_init() {
        assert_eq!(
            owned_specs("runtime/host.py", &["contracts", "runtime"], "acme", "import acme\n"),
            ["../__init__.py"]
        );
        assert_eq!(
            owned_specs(
                "runtime/host.py",
                &["contracts", "runtime"],
                "acme",
                "from acme import contracts\n"
            ),
            ["../__init__.py", "../contracts.py", "../contracts/__init__.py"]
        );
    }

    // A manifest's PyPI-style hyphenated name is never how the code spells it —
    // hyphens are not legal in a Python identifier — so the match folds `-` to `_`
    // the same way installing the package already does.
    #[test]
    fn a_hyphenated_declared_name_matches_its_underscored_import() {
        assert_eq!(
            owned_specs(
                "mod.py",
                &["contracts"],
                "my-package",
                "from my_package.contracts import X\n"
            ),
            ["contracts.py", "contracts/__init__.py", "contracts/X.py", "contracts/X/__init__.py"]
        );
    }

    // A package that genuinely nests under a directory of its own name is not this
    // rule's business — `roots` already resolves it, and stripping the leading
    // segment here would silently drop a real path component.
    #[test]
    fn a_package_that_already_has_a_directory_of_its_own_name_is_untouched() {
        assert_eq!(
            owned_specs("mod.py", &["acme"], "acme", "from acme.contracts import X\n"),
            [
                "acme/__init__.py",
                "acme/contracts.py",
                "acme/contracts/__init__.py",
                "acme/contracts/X.py",
                "acme/contracts/X/__init__.py",
            ]
        );
    }

    #[test]
    fn raise_from_and_yield_from_are_not_import_statements() {
        let src = "\
def f():
    raise ValueError() from cause
    yield from other()
";
        assert_eq!(specs("mod.py", &[], src), Vec::<String>::new());
    }

    #[test]
    fn indented_and_semicolon_separated_imports_are_still_statements() {
        let src = "\
if True:
    import os
import sys; import re
";
        assert_eq!(specs("mod.py", &[], src), ["os", "sys", "re"]);
    }

    #[test]
    fn a_backslash_continues_a_name_list_onto_the_next_line() {
        // Both halves of a joined statement are one statement: the names after the
        // break are imports like any other, and the backslash is never one itself.
        assert_eq!(specs("mod.py", &[], "import os, \\\n    sys\n"), ["os", "sys"]);
        assert_eq!(
            specs("mod.py", &[], "from collections import abc, \\\n    OrderedDict\n"),
            ["collections"]
        );
    }

    #[test]
    fn a_backslash_continues_a_from_clause_before_its_import() {
        assert_eq!(specs("mod.py", &[], "from os \\\n    import path\n"), ["os"]);
    }

    #[test]
    fn only_the_word_import_counts_not_a_longer_identifier() {
        assert_eq!(
            specs("mod.py", &[], "import_module('x')\nreimport = 1\n"),
            Vec::<String>::new()
        );
    }

    // Importing a leaf initializes every package above it, so each ancestor's
    // `__init__.py` is an edge the importer really has. Reading only the leaf let a
    // contract place an ancestor's `__init__.py` above the importer and still pass, which
    // is a stack no interpreter could honour.
    #[test]
    fn an_absolute_import_depends_on_every_ancestor_it_initializes() {
        assert_eq!(
            specs("low/consumer.py", &["mid"], "import mid.deep.leaf\n"),
            [
                "../mid/__init__.py",
                "../mid/deep/__init__.py",
                "../mid/deep/leaf.py",
                "../mid/deep/leaf/__init__.py",
            ]
        );
        assert_eq!(
            specs("low/consumer.py", &["mid"], "from mid.deep.leaf import LEAF\n"),
            [
                "../mid/__init__.py",
                "../mid/deep/__init__.py",
                "../mid/deep/leaf.py",
                "../mid/deep/leaf/__init__.py",
                "../mid/deep/leaf/LEAF.py",
                "../mid/deep/leaf/LEAF/__init__.py",
            ]
        );
    }

    // The ordinary absolute self-import, written from inside the package it names. Every
    // Python package with a non-empty `__init__.py` does this, and it is not a dependency
    // on the package root: nothing under `principia/` runs until `principia/__init__.py`
    // already has. Counting it made a real binding (principia's) report a four-directory
    // cycle through its own root.
    #[test]
    fn a_file_owes_nothing_to_the_package_root_it_already_lives_under() {
        assert_eq!(
            specs("principia/linalg/ops.py", &["principia"], "from principia._loader import ffi\n"),
            [
                "../../principia/_loader.py",
                "../../principia/_loader/__init__.py",
                "../../principia/_loader/ffi.py",
                "../../principia/_loader/ffi/__init__.py",
            ]
        );
    }

    // A relative import climbs the importer's own ancestors, and those ran before this
    // module's first line did — reaching through them takes on nothing new, so counting
    // them would invent an edge (and a file's dependency on its own parent package).
    #[test]
    fn a_relative_import_owes_nothing_to_the_ancestors_it_climbs_through() {
        assert_eq!(
            specs("mid/deep/mod.py", &["mid"], "from ..other.leaf import X\n"),
            [
                "../other/leaf.py",
                "../other/leaf/__init__.py",
                "../other/leaf/X.py",
                "../other/leaf/X/__init__.py",
            ]
        );
    }

    #[test]
    fn is_local_distinguishes_a_produced_path_from_a_module_name() {
        assert!(Python.is_local("../pkg/a.py"));
        assert!(!Python.is_local("numpy"));
        assert!(!Python.is_local("os"));
    }

    #[test]
    fn declared_reads_the_pep_621_project_name() {
        let manifest = "\
[build-system]
requires = [\"hatchling\"]

[project]
name = \"my-package\"
version = \"0.1.0\"
";
        assert_eq!(Python.declared(manifest).as_deref(), Some("my-package"));
        // A commented-out name must not win, matching the import lexer's own discipline.
        let manifest = "\
[project]
# name = \"wrong\"
name = \"right\"
";
        assert_eq!(Python.declared(manifest).as_deref(), Some("right"));
        assert_eq!(Python.declared("[tool.other]\nname = \"x\"\n"), None);
    }

    #[test]
    fn vendored_reads_path_dependencies() {
        let manifest = "\
[tool.uv.sources]
mypackage = { path = \"../mypackage\" }
";
        assert_eq!(Python.vendored(manifest), ["../mypackage"]);
    }

    #[test]
    fn stdlib_covers_the_modules_every_supported_interpreter_ships() {
        for name in ["os", "sys", "typing", "__future__", "tomllib", "dataclasses"] {
            assert!(STDLIB.contains(&name), "{name} should be ambient");
        }
    }
}