1use std::any::TypeId;
4use std::collections::HashSet;
5
6use crate::{Diagnostic, Error, MADS008, ModuleDescriptor, Result, SourceLocation};
7
8pub struct ModuleNode {
10 type_id: TypeId,
11 type_name: &'static str,
12 namespace: &'static str,
13 location: SourceLocation,
14}
15
16impl ModuleNode {
17 pub const fn type_id(&self) -> TypeId {
19 self.type_id
20 }
21
22 pub const fn type_name(&self) -> &'static str {
24 self.type_name
25 }
26
27 pub const fn namespace(&self) -> &'static str {
29 self.namespace
30 }
31
32 pub const fn location(&self) -> SourceLocation {
34 self.location
35 }
36}
37
38pub struct ModuleImportEdge {
40 importer: usize,
41 imported: usize,
42}
43
44impl ModuleImportEdge {
45 pub fn importer<'a>(&self, graph: &'a ModuleGraph) -> &'a ModuleNode {
47 &graph.modules[self.importer]
48 }
49
50 pub fn imported<'a>(&self, graph: &'a ModuleGraph) -> &'a ModuleNode {
52 &graph.modules[self.imported]
53 }
54}
55
56pub struct ProviderOwnership {
58 pub(crate) provider_type_name: &'static str,
59 pub(crate) module_type_name: Option<&'static str>,
60}
61
62impl ProviderOwnership {
63 pub const fn provider_type_name(&self) -> &'static str {
65 self.provider_type_name
66 }
67
68 pub const fn module_type_name(&self) -> Option<&'static str> {
70 self.module_type_name
71 }
72}
73
74pub struct ModuleGraph {
76 root: usize,
77 modules: Vec<ModuleNode>,
78 imports: Vec<ModuleImportEdge>,
79 provider_ownership: Vec<ProviderOwnership>,
80}
81
82impl ModuleGraph {
83 pub fn root(&self) -> &ModuleNode {
85 &self.modules[self.root]
86 }
87
88 pub fn modules(&self) -> &[ModuleNode] {
90 &self.modules
91 }
92
93 pub fn imports(&self) -> &[ModuleImportEdge] {
95 &self.imports
96 }
97
98 pub fn provider_ownership(&self) -> &[ProviderOwnership] {
100 &self.provider_ownership
101 }
102
103 #[doc(hidden)]
105 pub fn owner_for_namespace(&self, namespace: &str) -> Option<&ModuleNode> {
106 self.modules
107 .iter()
108 .filter(|module| namespace_contains(module.namespace(), namespace))
109 .max_by_key(|module| module.namespace().len())
110 }
111
112 #[doc(hidden)]
114 pub fn directly_imports(&self, importer: TypeId, imported: TypeId) -> bool {
115 self.imports.iter().any(|edge| {
116 edge.importer(self).type_id() == importer && edge.imported(self).type_id() == imported
117 })
118 }
119
120 #[allow(dead_code)]
121 pub(crate) fn is_reachable(&self, module: TypeId) -> bool {
122 self.modules
123 .iter()
124 .any(|candidate| candidate.type_id() == module)
125 }
126
127 #[allow(dead_code)]
128 pub(crate) fn set_provider_ownership(&mut self, ownership: Vec<ProviderOwnership>) {
129 self.provider_ownership = ownership;
130 }
131}
132
133pub(crate) fn build_module_graph(
134 root_type_id: TypeId,
135 modules: &[&'static ModuleDescriptor],
136) -> Result<ModuleGraph> {
137 let mut state = BuildState {
138 descriptors: modules,
139 visited: HashSet::new(),
140 stack: Vec::new(),
141 modules: Vec::new(),
142 imports: Vec::new(),
143 };
144 visit(root_type_id, &mut state)?;
145 let root = state
146 .node_index(root_type_id)
147 .expect("successful traversal records the root module");
148
149 Ok(ModuleGraph {
150 root,
151 modules: state.modules,
152 imports: state.imports,
153 provider_ownership: Vec::new(),
154 })
155}
156
157pub(crate) fn validate_module_catalog(modules: &[&'static ModuleDescriptor]) -> Result<()> {
158 for (index, descriptor) in modules.iter().copied().enumerate() {
159 let Some(namespace) = descriptor.namespace() else {
160 continue;
161 };
162 let conflicts = modules
163 .iter()
164 .copied()
165 .enumerate()
166 .filter(|(candidate_index, candidate)| {
167 *candidate_index != index && candidate.namespace() == Some(namespace)
168 })
169 .map(|(_, candidate)| candidate)
170 .collect::<Vec<_>>();
171 if !conflicts.is_empty() {
172 return Err(module_namespace_error(descriptor, &conflicts));
173 }
174 }
175
176 Ok(())
177}
178
179fn visit(module: TypeId, state: &mut BuildState<'_>) -> Result<()> {
180 if let Some(cycle_start) = state.stack.iter().position(|id| *id == module) {
181 return Err(state.module_cycle_error(&state.stack[cycle_start..], module));
182 }
183 if !state.visited.insert(module) {
184 return Ok(());
185 }
186
187 let descriptor = state.require_descriptor(module)?;
188 state.validate_unique_namespace(descriptor)?;
189 let node = state.push_node(descriptor)?;
190 state.stack.push(module);
191 state.validate_duplicate_direct_imports(descriptor)?;
192 for import in descriptor.imports() {
193 let imported = state.require_descriptor(import.type_id())?;
194 let imported_node = state.ensure_node(imported)?;
195 state.push_edge(node, imported_node);
196 visit(import.type_id(), state)?;
197 }
198 state.stack.pop();
199 Ok(())
200}
201
202struct BuildState<'a> {
203 descriptors: &'a [&'static ModuleDescriptor],
204 visited: HashSet<TypeId>,
205 stack: Vec<TypeId>,
206 modules: Vec<ModuleNode>,
207 imports: Vec<ModuleImportEdge>,
208}
209
210impl BuildState<'_> {
211 fn require_descriptor(&self, type_id: TypeId) -> Result<&'static ModuleDescriptor> {
212 let mut matches = self
213 .descriptors
214 .iter()
215 .copied()
216 .filter(|descriptor| descriptor.type_id() == type_id)
217 .collect::<Vec<_>>();
218 matches.sort_by(|left, right| {
219 left.type_name()
220 .cmp(right.type_name())
221 .then_with(|| location_order(left.location(), right.location()))
222 });
223
224 match matches.as_slice() {
225 [] => Err(Error::new(
226 Diagnostic::new(
227 MADS008,
228 "missing module metadata",
229 "a rooted module or direct import has no static module declaration",
230 )
231 .with_subject("requested module"),
232 )),
233 [descriptor] => Ok(*descriptor),
234 [first, rest @ ..] => {
235 let primary = Diagnostic::new(
236 MADS008,
237 "ambiguous module metadata",
238 "a module type has more than one static declaration",
239 )
240 .with_subject(first.type_name())
241 .with_location(first.location());
242 let related = rest.iter().map(|descriptor| {
243 Diagnostic::new(
244 MADS008,
245 "conflicting module declaration",
246 "this declaration describes the same module type",
247 )
248 .with_subject(descriptor.type_name())
249 .with_location(descriptor.location())
250 });
251 Err(Error::from_diagnostics(primary, related))
252 }
253 }
254 }
255
256 fn validate_unique_namespace(&self, descriptor: &ModuleDescriptor) -> Result<()> {
257 let Some(namespace) = descriptor.namespace() else {
258 return Err(Error::new(
259 Diagnostic::new(
260 MADS008,
261 "missing module namespace",
262 "rooted module graphs require namespace metadata",
263 )
264 .with_subject(descriptor.type_name())
265 .with_location(descriptor.location()),
266 ));
267 };
268
269 let conflicts = self
270 .descriptors
271 .iter()
272 .copied()
273 .filter(|candidate| {
274 candidate.type_id() != descriptor.type_id()
275 && candidate.namespace() == Some(namespace)
276 })
277 .collect::<Vec<_>>();
278 if !conflicts.is_empty() {
279 return Err(module_namespace_error(descriptor, &conflicts));
280 }
281
282 Ok(())
283 }
284
285 fn validate_duplicate_direct_imports(&self, descriptor: &ModuleDescriptor) -> Result<()> {
286 let mut seen = Vec::new();
287 for import in descriptor.imports() {
288 let imported = import.type_id();
289 if seen.contains(&imported) {
290 return Err(Error::new(
291 Diagnostic::new(
292 MADS008,
293 "duplicate direct module import",
294 format!(
295 "module `{}` appears more than once in the direct import list",
296 import.type_name()
297 ),
298 )
299 .with_subject(descriptor.type_name())
300 .with_location(descriptor.location()),
301 ));
302 }
303 seen.push(imported);
304 }
305 Ok(())
306 }
307
308 fn push_node(&mut self, descriptor: &ModuleDescriptor) -> Result<usize> {
309 self.ensure_node(descriptor)
310 }
311
312 fn ensure_node(&mut self, descriptor: &ModuleDescriptor) -> Result<usize> {
313 if let Some(index) = self.node_index(descriptor.type_id()) {
314 return Ok(index);
315 }
316 let Some(namespace) = descriptor.namespace() else {
317 return Err(Error::new(
318 Diagnostic::new(
319 MADS008,
320 "missing module namespace",
321 "rooted module graphs require namespace metadata",
322 )
323 .with_subject(descriptor.type_name())
324 .with_location(descriptor.location()),
325 ));
326 };
327 let index = self.modules.len();
328 self.modules.push(ModuleNode {
329 type_id: descriptor.type_id(),
330 type_name: descriptor.type_name(),
331 namespace,
332 location: descriptor.location(),
333 });
334 Ok(index)
335 }
336
337 fn push_edge(&mut self, importer: usize, imported: usize) {
338 self.imports.push(ModuleImportEdge { importer, imported });
339 }
340
341 fn node_index(&self, type_id: TypeId) -> Option<usize> {
342 self.modules
343 .iter()
344 .position(|module| module.type_id() == type_id)
345 }
346
347 fn module_cycle_error(&self, cycle: &[TypeId], repeated: TypeId) -> Error {
348 let mut chain = cycle
349 .iter()
350 .filter_map(|type_id| self.descriptor_for_stack(*type_id))
351 .collect::<Vec<_>>();
352 if let Some(repeated) = self.descriptor_for_stack(repeated) {
353 chain.push(repeated);
354 }
355 let subject = chain
356 .iter()
357 .map(|descriptor| descriptor.type_name())
358 .collect::<Vec<_>>()
359 .join(" -> ");
360 let primary_descriptor = chain
361 .first()
362 .expect("cycle members were already resolved during traversal");
363 let primary = Diagnostic::new(
364 MADS008,
365 "module import cycle",
366 "reachable module imports form a cycle",
367 )
368 .with_subject(subject.clone())
369 .with_location(primary_descriptor.location());
370 let related = chain
371 .iter()
372 .skip(1)
373 .take(chain.len().saturating_sub(2))
374 .map(|descriptor| {
375 Diagnostic::new(
376 MADS008,
377 "module in import cycle",
378 "this module participates in the import cycle",
379 )
380 .with_subject(subject.clone())
381 .with_location(descriptor.location())
382 });
383 Error::from_diagnostics(primary, related)
384 }
385
386 fn descriptor_for_stack(&self, type_id: TypeId) -> Option<&'static ModuleDescriptor> {
387 self.descriptors
388 .iter()
389 .copied()
390 .find(|descriptor| descriptor.type_id() == type_id)
391 }
392}
393
394fn module_namespace_error(descriptor: &ModuleDescriptor, conflicts: &[&ModuleDescriptor]) -> Error {
395 let namespace = descriptor
396 .namespace()
397 .expect("namespace collision candidates have namespace metadata");
398 let primary = Diagnostic::new(
399 MADS008,
400 "ambiguous module namespace",
401 "multiple module declarations claim the same Rust namespace",
402 )
403 .with_subject(namespace)
404 .with_location(descriptor.location());
405 let related = conflicts.iter().map(|conflict| {
406 Diagnostic::new(
407 MADS008,
408 "conflicting module namespace declaration",
409 "this module declaration claims the same namespace",
410 )
411 .with_subject(namespace)
412 .with_location(conflict.location())
413 });
414 Error::from_diagnostics(primary, related)
415}
416
417fn namespace_contains(parent: &str, child: &str) -> bool {
418 child == parent
419 || child
420 .strip_prefix(parent)
421 .is_some_and(|suffix| suffix.starts_with("::"))
422}
423
424fn location_order(left: SourceLocation, right: SourceLocation) -> std::cmp::Ordering {
425 left.file
426 .cmp(right.file)
427 .then_with(|| left.line.cmp(&right.line))
428 .then_with(|| left.column.cmp(&right.column))
429}