nova-driver 0.3.2

The Nova language's compilation pipeline (internal to the nova toolchain)
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
//! What the driver loads (spec
//! `docs/superpowers/specs/2026-10-08-phase-3-3a-local-packages-design.md`
//! §4): a [`Program`] names its roots and carries the package graph, and
//! [`load_program`] decides what each `import` names.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};

use nova_diagnostics::{Diagnostic, FileDb, FileId, Severity, Span};
use nova_pm::{Edge, Graph, GraphPackage, Offline, PackageId};
use nova_resolver::ImportTarget;

use crate::analyze::Sources;

/// The roots a command takes (spec §4.4's table), each only if it exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Roots {
    /// `src/main.nova`: `nova run` and `nova build`.
    Program,
    /// `src/main.nova`, then `src/lib.nova`: `nova check`.
    Check,
    /// Those, then `tests/*.nova` sorted by name: `nova test` and the
    /// language server.
    Test,
}

/// Where a root is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RootKind {
    /// Directly in the root package's `src/`.
    Src,
    /// Directly in the root package's `tests/`.
    Tests,
    /// In no package (spec §4.1).
    Loose,
    /// A doc test module (spec
    /// `docs/superpowers/specs/2026-10-11-phase-3-5b-doc-tests-design.md`
    /// §5), at a path of its own that need not be on disk. In a package's
    /// program it imports what a `tests/` module imports, and no file
    /// beside it; without a graph (std's doc tests) it imports nothing. A
    /// program with one keeps only the test each doc test module adds.
    Doc,
}

/// A file the loader starts from.
#[derive(Debug, Clone)]
pub struct Root {
    pub path: PathBuf,
    pub kind: RootKind,
}

/// What to load (spec §4.4).
pub struct Program {
    /// Every manifest the graph read. The loader adds every source file.
    pub db: FileDb,
    /// `None` for a loose program, or when the root's manifest cannot be
    /// read or parsed.
    pub graph: Option<Graph>,
    /// The entry first.
    pub roots: Vec<Root>,
    /// Whether MIR runs: the entry is `src/main.nova`, or a loose file.
    pub runs: bool,
    /// The graph's diagnostics.
    pub diagnostics: Vec<Diagnostic>,
}

impl Program {
    /// A loose program: `path`, and the files beside it that it imports.
    pub fn loose(path: &Path) -> Program {
        Program {
            db: FileDb::new(),
            graph: None,
            roots: vec![Root {
                path: path.to_path_buf(),
                kind: RootKind::Loose,
            }],
            runs: true,
            diagnostics: Vec::new(),
        }
    }

    /// The program whose entry is `path` (spec §4.1). It is a module of its
    /// package when it is directly in a package's `src/` or `tests/`, and
    /// otherwise loose, reading no manifest.
    pub fn for_file(path: &Path) -> Program {
        let Some((root, kind)) = package_of(path) else {
            return Program::loose(path);
        };
        let mut db = FileDb::new();
        let (graph, diagnostics) = nova_pm::graph(&root, &mut db);
        let runs = kind == RootKind::Src && path.file_stem().is_some_and(|stem| stem == "main");
        Program {
            db,
            graph,
            roots: vec![Root {
                path: path.to_path_buf(),
                kind,
            }],
            runs,
            diagnostics,
        }
    }

    /// The package whose `nova.toml` is in `root` (empty for the current
    /// directory), with the roots `roots` names that exist.
    pub fn for_package(root: &Path, roots: Roots) -> Program {
        Program::for_package_in(root, roots, &Offline::from_env())
    }

    /// [`Program::for_package`], with registry packages found as `offline`
    /// says (spec 3.3b §5.4): tests pass the registry directory, and
    /// publishing's verification reads no dev-dependencies.
    pub fn for_package_in(root: &Path, roots: Roots, offline: &Offline) -> Program {
        let mut db = FileDb::new();
        let (graph, diagnostics) = nova_pm::graph_with(root, None, offline, &mut db);
        let mut list = Vec::new();
        let main = under(root, "src/main.nova");
        if main.is_file() {
            list.push(Root {
                path: main,
                kind: RootKind::Src,
            });
        }
        let runs = !list.is_empty();
        let lib = under(root, "src/lib.nova");
        if roots != Roots::Program && lib.is_file() {
            list.push(Root {
                path: lib,
                kind: RootKind::Src,
            });
        }
        if roots == Roots::Test {
            list.extend(
                test_files(&under(root, "tests"))
                    .into_iter()
                    .map(|path| Root {
                        path,
                        kind: RootKind::Tests,
                    }),
            );
        }
        Program {
            db,
            graph,
            roots: list,
            runs,
            diagnostics,
        }
    }

    /// A program of doc tests (spec 3.5b §5, §6.2), each of `paths` a
    /// [`RootKind::Doc`] root, read through the `Sources` given to
    /// `build_test_program_with`: of the package whose `nova.toml` is in
    /// `package`, or of no package for std's (`None`).
    ///
    /// A package's library, `src/lib.nova`, is a root after them. The
    /// loader then reads it under the path the root names, as `nova doc`'s
    /// analysis does, rather than the one an import names, which differs on
    /// Windows under an empty root; a diagnostic's map finds the library in
    /// the database by that name (spec 3.5b §7). The first doc test stays
    /// the entry, which names the binary apart from the unit tests'.
    ///
    /// With no `paths` there is no root, and a build fails with "nothing
    /// to compile" rather than build the library's own tests.
    pub fn doc_tests(package: Option<&Path>, paths: Vec<PathBuf>) -> Program {
        let mut roots: Vec<Root> = paths
            .into_iter()
            .map(|path| Root {
                path,
                kind: RootKind::Doc,
            })
            .collect();
        match package {
            Some(root) => {
                let lib = under(root, "src/lib.nova");
                if !roots.is_empty() && lib.is_file() {
                    roots.push(Root {
                        path: lib,
                        kind: RootKind::Src,
                    });
                }
                Program {
                    roots,
                    runs: false,
                    ..Program::for_package(root, Roots::Program)
                }
            }
            None => Program {
                db: FileDb::new(),
                graph: None,
                roots,
                runs: false,
                diagnostics: Vec::new(),
            },
        }
    }

    /// Whether the graph found an error.
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.severity == Severity::Error)
    }

    /// The root package's `nova.toml` in `db`, once read. The language
    /// server publishes the graph's problems under it (spec §6).
    pub fn manifest(&self) -> Option<FileId> {
        match &self.graph {
            Some(graph) => Some(graph.root().manifest_file),
            // Without a graph only the root's manifest was read, and each of
            // its diagnostics is labelled in it.
            None => self
                .diagnostics
                .iter()
                .flat_map(|d| &d.labels)
                .map(|label| label.span.file)
                .next(),
        }
    }
}

/// `relative`, a `/`-separated path, under `root`. Under an empty root it
/// is `relative` as written, so `nova run` at a project's root still names
/// `src/main.nova` on every system, as it always has.
fn under(root: &Path, relative: &str) -> PathBuf {
    if root.as_os_str().is_empty() {
        PathBuf::from(relative)
    } else {
        relative
            .split('/')
            .fold(root.to_path_buf(), |path, part| path.join(part))
    }
}

/// The package `path` is a module of, and where in it, when `path` is
/// directly in the `src/` or `tests/` of a directory holding a `nova.toml`
/// (spec §4.1). The language server finds its projects the same way.
pub fn package_of(path: &Path) -> Option<(PathBuf, RootKind)> {
    let parent = path.parent()?;
    let kind = match parent.file_name()?.to_str()? {
        "src" => RootKind::Src,
        "tests" => RootKind::Tests,
        _ => return None,
    };
    let root = parent.parent()?;
    root.join(nova_pm::MANIFEST)
        .is_file()
        .then(|| (root.to_path_buf(), kind))
}

/// The `*.nova` files directly in `dir`, sorted by name (spec §4.4). A
/// missing directory has none.
fn test_files(dir: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut files: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "nova") && path.is_file())
        .collect();
    files.sort();
    files
}

/// The files of `modules` that belong to a registry package (spec 3.3b
/// §5.4). A registry manifest's warnings never leave the graph.
pub(crate) fn registry_files(graph: Option<&Graph>, modules: &[Loaded]) -> HashSet<FileId> {
    let Some(graph) = graph else {
        return HashSet::new();
    };
    modules
        .iter()
        .filter(|m| m.package.is_some_and(|p| graph.package(p).registry))
        .map(|m| m.file)
        .collect()
}

/// Whether `d` is a warning about a registry package alone, which is not
/// shown, as Cargo caps a dependency's lints: it has a label, and every
/// label is in `registry`.
pub(crate) fn a_dependencys_warning(d: &Diagnostic, registry: &HashSet<FileId>) -> bool {
    d.severity == Severity::Warning
        && !d.labels.is_empty()
        && d.labels
            .iter()
            .all(|label| registry.contains(&label.span.file))
}

/// One module [`load_program`] read.
pub(crate) struct Loaded {
    /// A label for messages (spec §4.5): `utils`, `tests/utils`, `geom` or
    /// `geom/utils`.
    pub name: String,
    pub path: PathBuf,
    pub file: FileId,
    pub ast: nova_ast::File,
    /// Its package. `None` for a loose module.
    pub package: Option<PackageId>,
    /// Whether it is directly in its package's `tests/`, or a doc test
    /// module: its tests are named `<file stem>::<function>`.
    pub test_file: bool,
    /// Whether it is a doc test module (spec 3.5b §6.2).
    pub doc: bool,
    /// What each of its imports names, by first segment (spec §4.3).
    pub imports: HashMap<String, ImportTarget>,
    /// Every loaded module it could import, by the name an import of it
    /// writes (spec 3.4b §4.6).
    pub importable: Vec<(String, usize)>,
}

/// What [`load_program`] found.
#[derive(Default)]
pub(crate) struct Load {
    /// In load order: `modules[i]` is `ModuleId(i)`.
    pub modules: Vec<Loaded>,
    /// Lex, parse and import diagnostics, in load order.
    pub diagnostics: Vec<Diagnostic>,
    /// The names of the items the parser dropped.
    pub dropped: Vec<String>,
}

/// A module's identity (spec §4.2).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Place {
    /// A file directly in a package's `src/`, or `tests/` when `tests`.
    Package {
        package: PackageId,
        tests: bool,
        stem: String,
    },
    /// A loose file.
    Loose { dir: PathBuf, stem: String },
    /// A doc test module, by its path (spec 3.5b §5): of the root package,
    /// or of none for std's. Nothing imports one.
    Doc {
        package: Option<PackageId>,
        path: PathBuf,
    },
}

impl Place {
    fn package(&self) -> Option<PackageId> {
        match self {
            Place::Package { package, .. } => Some(*package),
            Place::Loose { .. } => None,
            Place::Doc { package, .. } => *package,
        }
    }

    fn is_test(&self) -> bool {
        matches!(self, Place::Package { tests: true, .. } | Place::Doc { .. })
    }

    fn is_doc(&self) -> bool {
        matches!(self, Place::Doc { .. })
    }
}

/// What an import names, before every module is loaded.
enum Pending {
    Place(Place),
    Reported,
}

/// What [`Loader::find`] found for one import.
enum Found {
    /// A module: its identity and its file.
    Module(Place, PathBuf),
    /// An error, reported here (spec §4.3, rules 3–5).
    Reported(Diagnostic),
    /// Nothing: the resolver reports "cannot find module".
    Nothing,
}

/// Read, lex and parse every module the roots reach, breadth first from the
/// roots in order (spec §4.4), deciding what each import names (§4.3).
///
/// A module that cannot be read is skipped, and an import of it is then
/// "cannot find module". `Err` only when the entry itself cannot be read.
/// Without a graph, every root is loose.
pub(crate) fn load_program(
    graph: Option<&Graph>,
    roots: &[Root],
    sources: &dyn Sources,
    db: &mut FileDb,
) -> std::io::Result<Load> {
    let mut loader = Loader {
        graph,
        sources,
        listings: HashMap::new(),
        known: HashMap::new(),
    };
    let mut load = Load::default();
    let mut pending: Vec<Vec<(String, Pending)>> = Vec::new();
    let mut places: HashMap<Place, usize> = HashMap::new();
    let mut tried: HashSet<Place> = HashSet::new();
    let mut queue: VecDeque<(Place, PathBuf)> = roots
        .iter()
        .map(|root| (loader.root_place(root), root.path.clone()))
        .collect();
    let mut is_entry = true;

    while let Some((place, path)) = queue.pop_front() {
        let entry = std::mem::replace(&mut is_entry, false);
        if !tried.insert(place.clone()) {
            continue;
        }
        let source = match sources.read(&path) {
            Ok(source) => source,
            Err(e) if entry => return Err(e),
            Err(_) => continue,
        };
        let file = db.add(path.display().to_string(), source.as_str());

        let (tokens, lex_errors) = nova_lexer::lex(&source, file);
        load.diagnostics.extend(lex_errors.iter().map(|e| {
            Diagnostic::error("L0001", e.to_string()).with_primary_label(e.span(), "here")
        }));
        let parsed = nova_parser::parse_recovering(&tokens, file);
        load.diagnostics.extend(parsed.errors.iter().map(|e| {
            Diagnostic::error("P0001", e.to_string()).with_primary_label(e.span(), "here")
        }));
        load.dropped
            .extend(parsed.dropped.into_iter().map(|n| n.value));

        // Only a single-segment import names a module; the resolver rejects
        // the others.
        let mut imports = Vec::new();
        for item in &parsed.file.items {
            let nova_ast::Item::Import(import) = &item.value else {
                continue;
            };
            let [segment] = import.path.value.segments.as_slice() else {
                continue;
            };
            let name = segment.value.clone();
            match loader.find(&place, &name, import.path.span, db) {
                Found::Module(target, target_path) => {
                    queue.push_back((target.clone(), target_path));
                    imports.push((name, Pending::Place(target)));
                }
                Found::Reported(diagnostic) => {
                    load.diagnostics.push(diagnostic);
                    imports.push((name, Pending::Reported));
                }
                Found::Nothing => {}
            }
        }
        places.insert(place.clone(), load.modules.len());
        load.modules.push(Loaded {
            name: loader.label(&place),
            path,
            file,
            ast: parsed.file,
            package: place.package(),
            test_file: place.is_test(),
            doc: place.is_doc(),
            imports: HashMap::new(),
            importable: Vec::new(),
        });
        pending.push(imports);
    }

    for (module, imports) in load.modules.iter_mut().zip(pending) {
        for (name, target) in imports {
            let target = match target {
                Pending::Place(place) => match places.get(&place) {
                    Some(&index) => ImportTarget::Module(index),
                    // It could not be read.
                    None => continue,
                },
                Pending::Reported => ImportTarget::Reported,
            };
            module.imports.insert(name, target);
        }
    }
    // Spec 3.4b §4.6 (plan decision 9): what each loaded module could
    // import, by the name an import of it writes, through `find` itself.
    let mut place_of: Vec<Option<Place>> = vec![None; load.modules.len()];
    for (place, &i) in &places {
        place_of[i] = Some(place.clone());
    }
    let nowhere = Span::point(0, FileId::DUMMY);
    let mut importables: Vec<Vec<(String, usize)>> = Vec::new();
    for (i, from) in place_of.iter().enumerate() {
        let mut importable = Vec::new();
        if let Some(from) = from {
            let mut names: Vec<String> = place_of
                .iter()
                .flatten()
                .filter_map(|p| sibling_stem(from, p))
                .collect();
            let edges = match (from, graph) {
                (Place::Package { package, tests, .. }, Some(graph)) => {
                    visible_edges(graph, *package, *tests)
                }
                (
                    Place::Doc {
                        package: Some(package),
                        ..
                    },
                    Some(graph),
                ) => visible_edges(graph, *package, true),
                _ => Vec::new(),
            };
            names.extend(edges.into_iter().map(|e| e.import_name));
            names.sort();
            names.dedup();
            for name in names {
                if let Found::Module(target, _) = loader.find(from, &name, nowhere, db) {
                    if let Some(&j) = places.get(&target) {
                        if j != i {
                            importable.push((name, j));
                        }
                    }
                }
            }
        }
        importables.push(importable);
    }
    for (module, importable) in load.modules.iter_mut().zip(importables) {
        module.importable = importable;
    }
    Ok(load)
}

struct Loader<'a> {
    graph: Option<&'a Graph>,
    sources: &'a dyn Sources,
    /// Each directory's file names, read once (spec §4.3, decision 5).
    listings: HashMap<PathBuf, Vec<String>>,
    /// Each `has` answered, by directory and stem: a name the listing lacks
    /// costs one read per load, not one per module (spec 3.5a §3,
    /// follow-up 2).
    known: HashMap<(PathBuf, String), bool>,
}

impl<'a> Loader<'a> {
    fn root_place(&self, root: &Root) -> Place {
        let stem = crate::FrontendContext::module_name(&root.path);
        match (root.kind, self.graph) {
            (RootKind::Src, Some(_)) => Place::Package {
                package: PackageId(0),
                tests: false,
                stem,
            },
            (RootKind::Tests, Some(_)) => Place::Package {
                package: PackageId(0),
                tests: true,
                stem,
            },
            (RootKind::Doc, graph) => Place::Doc {
                package: graph.map(|_| PackageId(0)),
                path: root.path.clone(),
            },
            _ => Place::Loose {
                dir: root
                    .path
                    .parent()
                    .map(Path::to_path_buf)
                    .unwrap_or_default(),
                stem,
            },
        }
    }

    /// The module's label (spec §4.5).
    fn label(&self, place: &Place) -> String {
        match place {
            Place::Loose { stem, .. } => stem.clone(),
            Place::Doc { path, .. } => format!("doc/{}", crate::FrontendContext::module_name(path)),
            Place::Package {
                package: PackageId(0),
                tests,
                stem,
            } => {
                if *tests {
                    format!("tests/{stem}")
                } else {
                    stem.clone()
                }
            }
            Place::Package { package, stem, .. } => {
                let import = &self.graph().package(*package).import_name;
                if stem == "lib" {
                    import.clone()
                } else {
                    format!("{import}/{stem}")
                }
            }
        }
    }

    /// The graph, borrowed for `'a` rather than from `self`, so `has` can
    /// run while it is held.
    fn graph(&self) -> &'a Graph {
        self.graph.expect("a package's module has a graph")
    }

    /// What `import name`, at `at` in the module at `from`, names (spec
    /// §4.3).
    fn find(&mut self, from: &Place, name: &str, at: Span, db: &FileDb) -> Found {
        let (package, tests, siblings) = match from {
            Place::Loose { dir, .. } => {
                if !self.has(dir, name) {
                    return Found::Nothing;
                }
                let place = Place::Loose {
                    dir: dir.clone(),
                    stem: name.to_string(),
                };
                return Found::Module(place, dir.join(format!("{name}.nova")));
            }
            Place::Package { package, tests, .. } => (*package, *tests, true),
            // What a `tests/` module sees, less the files beside it (spec
            // 3.5b §5.1).
            Place::Doc {
                package: Some(package),
                ..
            } => (*package, true, false),
            // std's doc tests import nothing.
            Place::Doc { package: None, .. } => return Found::Nothing,
        };
        let graph = self.graph();
        let dir = module_dir(graph.package(package), tests);
        let edge = visible_edges(graph, package, tests)
            .into_iter()
            .find(|edge| edge.import_name == name);
        let file = (siblings && self.has(&dir, name)).then(|| {
            (
                Place::Package {
                    package,
                    tests,
                    stem: name.to_string(),
                },
                dir.join(format!("{name}.nova")),
            )
        });
        match (file, edge) {
            (Some((_, path)), Some(edge)) => Found::Reported(clash(name, &path, &edge, at, db)),
            (Some((place, path)), None) => Found::Module(place, path),
            (None, Some(edge)) => {
                let target = graph.package(edge.package);
                if !target.has_lib {
                    // The package itself, seen from its own tests (rule 5).
                    return Found::Reported(
                        Diagnostic::error("E0001", format!("cannot find module `{name}`"))
                            .with_primary_label(at, "no such module")
                            .with_note(format!("`{}` has no src/lib.nova", target.name)),
                    );
                }
                Found::Module(
                    Place::Package {
                        package: edge.package,
                        tests: false,
                        stem: "lib".to_string(),
                    },
                    module_dir(target, false).join("lib.nova"),
                )
            }
            (None, None) => {
                let dev = !tests
                    && package == PackageId(0)
                    && graph
                        .root()
                        .dev_dependencies
                        .iter()
                        .any(|edge| edge.import_name == name);
                if dev {
                    Found::Reported(
                        Diagnostic::error("E0001", format!("cannot find module `{name}`"))
                            .with_primary_label(at, "no such module")
                            .with_note(format!(
                                "`{name}` is a dev-dependency, which only `tests/` files can import"
                            )),
                    )
                } else {
                    Found::Nothing
                }
            }
        }
    }

    /// Whether `dir` holds `<stem>.nova` ([`Loader::look`]), answered once
    /// per load (spec 3.5a §3, follow-up 2).
    fn has(&mut self, dir: &Path, stem: &str) -> bool {
        let key = (dir.to_path_buf(), stem.to_string());
        if let Some(&known) = self.known.get(&key) {
            return known;
        }
        let found = self.look(dir, stem);
        self.known.insert(key, found);
        found
    }

    /// Whether `dir` holds `<stem>.nova`, its name matching exactly (spec
    /// §4.3). A name the disk does not hold in any case may be an editor's
    /// unsaved buffer, read through `Sources`.
    ///
    /// An empty `dir`, a loose entry named without one (`nova run
    /// main.nova`), is the current directory: `read_dir("")` fails on every
    /// system, which would leave the case-insensitive read to decide.
    fn look(&mut self, dir: &Path, stem: &str) -> bool {
        let name = format!("{stem}.nova");
        let listed = if dir.as_os_str().is_empty() {
            Path::new(".")
        } else {
            dir
        };
        let listing = self.listings.entry(dir.to_path_buf()).or_insert_with(|| {
            std::fs::read_dir(listed)
                .map(|entries| {
                    entries
                        .filter_map(Result::ok)
                        .filter_map(|entry| entry.file_name().into_string().ok())
                        .collect()
                })
                .unwrap_or_default()
        });
        if listing.contains(&name) {
            return true;
        }
        if listing.iter().any(|n| n.eq_ignore_ascii_case(&name)) {
            return false;
        }
        self.sources.read(&dir.join(&name)).is_ok()
    }
}

/// A package's `src/`, or `tests/` when `tests`.
fn module_dir(package: &GraphPackage, tests: bool) -> PathBuf {
    package.dir.join(if tests { "tests" } else { "src" })
}

/// `p`'s stem when it is a module beside `from`: a loose file in the same
/// directory, or a module of the same package and directory (spec 3.4b
/// §4.6).
fn sibling_stem(from: &Place, p: &Place) -> Option<String> {
    match (from, p) {
        (Place::Loose { dir: a, .. }, Place::Loose { dir: b, stem }) if a == b => {
            Some(stem.clone())
        }
        (
            Place::Package {
                package: a,
                tests: s,
                ..
            },
            Place::Package {
                package: b,
                tests: t,
                stem,
            },
        ) if a == b && s == t => Some(stem.clone()),
        _ => None,
    }
}

/// The dependencies a module of `package` sees (spec §4.3). A test module
/// also sees the root's dev-dependencies, and the root itself by its import
/// name. Only the root's test modules are ever loaded.
fn visible_edges(graph: &Graph, package: PackageId, tests: bool) -> Vec<Edge> {
    let p = graph.package(package);
    let mut edges = p.dependencies.clone();
    if tests {
        edges.extend(p.dev_dependencies.iter().cloned());
        edges.push(Edge {
            import_name: p.import_name.clone(),
            package,
            span: p.manifest.package.span,
        });
    }
    edges
}

/// E0004 (spec §4.3, rule 3): `name` is both `file` and the dependency
/// `edge`. The message names both, so it reads in full where a related
/// label cannot show.
fn clash(name: &str, file: &Path, edge: &Edge, at: Span, db: &FileDb) -> Diagnostic {
    let manifest = db.get_name(edge.span.file).unwrap_or("nova.toml");
    let line = db
        .location(edge.span.file, edge.span.start)
        .map_or(0, |(line, _)| line);
    Diagnostic::error(
        "E0004",
        format!(
            "`{name}` is both a module of this package and a dependency: {}, and the entry \
             at {manifest}:{line}",
            file.display()
        ),
    )
    .with_primary_label(at, "this import is ambiguous")
    .with_secondary_label(edge.span, "the dependency")
}