1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::path::{Path, PathBuf};
4
5use rustc_ast::ast;
6use rustc_ast::visit::Visitor;
7use rustc_span::Span;
8use rustc_span::symbol::{self, Symbol, sym};
9use thin_vec::ThinVec;
10use thiserror::Error;
11
12use crate::attr::MetaVisitor;
13use crate::config::FileName;
14use crate::items::is_mod_decl;
15use crate::parse::parser::{
16 Directory, DirectoryOwnership, ModError, ModulePathSuccess, Parser, ParserError,
17};
18use crate::parse::session::ParseSess;
19use crate::utils::{contains_skip, mk_sp};
20
21mod visitor;
22
23type FileModMap<'ast> = BTreeMap<FileName, Module<'ast>>;
24
25#[derive(Debug, Clone)]
27pub(crate) struct Module<'a> {
28 ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
29 pub(crate) items: Cow<'a, ThinVec<Box<ast::Item>>>,
30 inner_attr: ast::AttrVec,
31 pub(crate) span: Span,
32}
33
34impl<'a> Module<'a> {
35 pub(crate) fn new(
36 mod_span: Span,
37 ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
38 mod_items: Cow<'a, ThinVec<Box<ast::Item>>>,
39 mod_attrs: Cow<'a, ast::AttrVec>,
40 ) -> Self {
41 let inner_attr = mod_attrs
42 .iter()
43 .filter(|attr| attr.style == ast::AttrStyle::Inner)
44 .cloned()
45 .collect();
46 Module {
47 items: mod_items,
48 inner_attr,
49 span: mod_span,
50 ast_mod_kind,
51 }
52 }
53
54 pub(crate) fn attrs(&self) -> &[ast::Attribute] {
55 &self.inner_attr
56 }
57}
58
59pub(crate) struct ModResolver<'ast, 'psess> {
61 psess: &'psess ParseSess,
62 directory: Directory,
63 file_map: FileModMap<'ast>,
64 recursive: bool,
65}
66
67#[derive(Debug, Error)]
69#[error("failed to resolve mod `{module}`: {kind}")]
70pub struct ModuleResolutionError {
71 pub(crate) module: String,
72 pub(crate) kind: ModuleResolutionErrorKind,
73}
74
75#[derive(Debug, Error)]
77pub(crate) enum ModuleResolutionErrorKind {
78 #[error("cannot parse {file}")]
80 ParseError { file: PathBuf },
81 #[error("{file} does not exist")]
83 NotFound { file: PathBuf },
84 #[error("file for module found at both {default_path:?} and {secondary_path:?}")]
86 MultipleCandidates {
87 default_path: PathBuf,
88 secondary_path: PathBuf,
89 },
90}
91
92#[derive(Clone)]
93enum SubModKind<'a, 'ast> {
94 External(PathBuf, DirectoryOwnership, Module<'ast>),
96 MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
98 Internal(&'a ast::Item),
100}
101
102impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> {
103 pub(crate) fn new(
105 psess: &'psess ParseSess,
106 directory_ownership: DirectoryOwnership,
107 recursive: bool,
108 ) -> Self {
109 ModResolver {
110 directory: Directory {
111 path: PathBuf::new(),
112 ownership: directory_ownership,
113 },
114 file_map: BTreeMap::new(),
115 psess,
116 recursive,
117 }
118 }
119
120 pub(crate) fn visit_crate(
122 mut self,
123 krate: &'ast ast::Crate,
124 ) -> Result<FileModMap<'ast>, ModuleResolutionError> {
125 let root_filename = self.psess.span_to_filename(krate.spans.inner_span);
126 self.directory.path = match root_filename {
127 FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
128 _ => PathBuf::new(),
129 };
130
131 if self.recursive {
133 self.visit_mod_from_ast(&krate.items)?;
134 }
135
136 let snippet_provider = self.psess.snippet_provider(krate.spans.inner_span);
137
138 self.file_map.insert(
139 root_filename,
140 Module::new(
141 mk_sp(snippet_provider.start_pos(), snippet_provider.end_pos()),
142 None,
143 Cow::Borrowed(&krate.items),
144 Cow::Borrowed(&krate.attrs),
145 ),
146 );
147 Ok(self.file_map)
148 }
149
150 fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> {
152 let mut visitor = visitor::CfgIfVisitor::new(self.psess);
153 visitor.visit_item(&item);
154 for module_item in visitor.mods() {
155 if let ast::ItemKind::Mod(_, _, ref sub_mod_kind) = module_item.item.kind {
156 self.visit_sub_mod(
157 &module_item.item,
158 Module::new(
159 module_item.item.span,
160 Some(Cow::Owned(sub_mod_kind.clone())),
161 Cow::Owned(ThinVec::new()),
162 Cow::Owned(ast::AttrVec::new()),
163 ),
164 )?;
165 }
166 }
167 Ok(())
168 }
169
170 fn visit_mod_outside_ast(
172 &mut self,
173 items: ThinVec<Box<ast::Item>>,
174 ) -> Result<(), ModuleResolutionError> {
175 for item in items {
176 if is_cfg_if(&item) {
177 self.visit_cfg_if(Cow::Owned(*item))?;
178 continue;
179 }
180
181 if let ast::ItemKind::Mod(_, _, ref sub_mod_kind) = item.kind {
182 let span = item.span;
183 self.visit_sub_mod(
184 &item,
185 Module::new(
186 span,
187 Some(Cow::Owned(sub_mod_kind.clone())),
188 Cow::Owned(ThinVec::new()),
189 Cow::Owned(ast::AttrVec::new()),
190 ),
191 )?;
192 }
193 }
194 Ok(())
195 }
196
197 fn visit_mod_from_ast(
199 &mut self,
200 items: &'ast [Box<ast::Item>],
201 ) -> Result<(), ModuleResolutionError> {
202 for item in items {
203 if is_cfg_if(item) {
204 self.visit_cfg_if(Cow::Borrowed(item))?;
205 }
206
207 if let ast::ItemKind::Mod(_, _, ref sub_mod_kind) = item.kind {
208 let span = item.span;
209 self.visit_sub_mod(
210 item,
211 Module::new(
212 span,
213 Some(Cow::Borrowed(sub_mod_kind)),
214 Cow::Owned(ThinVec::new()),
215 Cow::Borrowed(&item.attrs),
216 ),
217 )?;
218 }
219 }
220 Ok(())
221 }
222
223 fn visit_sub_mod(
224 &mut self,
225 item: &'c ast::Item,
226 sub_mod: Module<'ast>,
227 ) -> Result<(), ModuleResolutionError> {
228 let old_directory = self.directory.clone();
229 let sub_mod_kind = self.peek_sub_mod(item, &sub_mod)?;
230 if let Some(sub_mod_kind) = sub_mod_kind {
231 self.insert_sub_mod(sub_mod_kind.clone())?;
232 self.visit_sub_mod_inner(sub_mod, sub_mod_kind)?;
233 }
234 self.directory = old_directory;
235 Ok(())
236 }
237
238 fn peek_sub_mod(
240 &self,
241 item: &'c ast::Item,
242 sub_mod: &Module<'ast>,
243 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
244 if contains_skip(&item.attrs) {
245 return Ok(None);
246 }
247
248 if is_mod_decl(item) {
249 self.find_external_module(item.kind.ident().unwrap(), &item.attrs, sub_mod)
252 } else {
253 Ok(Some(SubModKind::Internal(item)))
255 }
256 }
257
258 fn insert_sub_mod(
259 &mut self,
260 sub_mod_kind: SubModKind<'c, 'ast>,
261 ) -> Result<(), ModuleResolutionError> {
262 match sub_mod_kind {
263 SubModKind::External(mod_path, _, sub_mod) => {
264 self.file_map
265 .entry(FileName::Real(mod_path))
266 .or_insert(sub_mod);
267 }
268 SubModKind::MultiExternal(mods) => {
269 for (mod_path, _, sub_mod) in mods {
270 self.file_map
271 .entry(FileName::Real(mod_path))
272 .or_insert(sub_mod);
273 }
274 }
275 _ => (),
276 }
277 Ok(())
278 }
279
280 fn visit_sub_mod_inner(
281 &mut self,
282 sub_mod: Module<'ast>,
283 sub_mod_kind: SubModKind<'c, 'ast>,
284 ) -> Result<(), ModuleResolutionError> {
285 match sub_mod_kind {
286 SubModKind::External(mod_path, directory_ownership, sub_mod) => {
287 let directory = Directory {
288 path: mod_path.parent().unwrap().to_path_buf(),
289 ownership: directory_ownership,
290 };
291 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))
292 }
293 SubModKind::Internal(item) => {
294 self.push_inline_mod_directory(item.kind.ident().unwrap(), &item.attrs);
295 self.visit_sub_mod_after_directory_update(sub_mod, None)
296 }
297 SubModKind::MultiExternal(mods) => {
298 for (mod_path, directory_ownership, sub_mod) in mods {
299 let directory = Directory {
300 path: mod_path.parent().unwrap().to_path_buf(),
301 ownership: directory_ownership,
302 };
303 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))?;
304 }
305 Ok(())
306 }
307 }
308 }
309
310 fn visit_sub_mod_after_directory_update(
311 &mut self,
312 sub_mod: Module<'ast>,
313 directory: Option<Directory>,
314 ) -> Result<(), ModuleResolutionError> {
315 if let Some(directory) = directory {
316 self.directory = directory;
317 }
318 match (sub_mod.ast_mod_kind, sub_mod.items) {
319 (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => {
320 self.visit_mod_from_ast(items)
321 }
322 (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => {
323 self.visit_mod_outside_ast(items)
324 }
325 (_, _) => Ok(()),
326 }
327 }
328
329 fn find_external_module(
331 &self,
332 mod_name: symbol::Ident,
333 attrs: &[ast::Attribute],
334 sub_mod: &Module<'ast>,
335 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
336 let relative = match self.directory.ownership {
337 DirectoryOwnership::Owned { relative } => relative,
338 DirectoryOwnership::UnownedViaBlock => None,
339 };
340 if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
341 if self.psess.is_file_parsed(&path) {
342 return Ok(None);
343 }
344 return match Parser::parse_file_as_module(self.psess, &path, sub_mod.span) {
345 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
346 Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
347 path,
348 DirectoryOwnership::Owned { relative: None },
349 Module::new(
350 span,
351 Some(Cow::Owned(ast::ModKind::Unloaded)),
352 Cow::Owned(items),
353 Cow::Owned(attrs),
354 ),
355 ))),
356 Err(ParserError::ParseError) => Err(ModuleResolutionError {
357 module: mod_name.to_string(),
358 kind: ModuleResolutionErrorKind::ParseError { file: path },
359 }),
360 Err(..) => Err(ModuleResolutionError {
361 module: mod_name.to_string(),
362 kind: ModuleResolutionErrorKind::NotFound { file: path },
363 }),
364 };
365 }
366
367 let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
369
370 match self
371 .psess
372 .default_submod_path(mod_name, relative, &self.directory.path)
373 {
374 Ok(ModulePathSuccess {
375 file_path,
376 dir_ownership,
377 ..
378 }) => {
379 let outside_mods_empty = mods_outside_ast.is_empty();
380 let should_insert = !mods_outside_ast
381 .iter()
382 .any(|(outside_path, _, _)| outside_path == &file_path);
383 if self.psess.is_file_parsed(&file_path) {
384 if outside_mods_empty {
385 return Ok(None);
386 } else {
387 if should_insert {
388 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
389 }
390 return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
391 }
392 }
393 match Parser::parse_file_as_module(self.psess, &file_path, sub_mod.span) {
394 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
395 Ok((attrs, items, span)) if outside_mods_empty => {
396 Ok(Some(SubModKind::External(
397 file_path,
398 dir_ownership,
399 Module::new(
400 span,
401 Some(Cow::Owned(ast::ModKind::Unloaded)),
402 Cow::Owned(items),
403 Cow::Owned(attrs),
404 ),
405 )))
406 }
407 Ok((attrs, items, span)) => {
408 mods_outside_ast.push((
409 file_path.clone(),
410 dir_ownership,
411 Module::new(
412 span,
413 Some(Cow::Owned(ast::ModKind::Unloaded)),
414 Cow::Owned(items),
415 Cow::Owned(attrs),
416 ),
417 ));
418 if should_insert {
419 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
420 }
421 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
422 }
423 Err(ParserError::ParseError) => Err(ModuleResolutionError {
424 module: mod_name.to_string(),
425 kind: ModuleResolutionErrorKind::ParseError { file: file_path },
426 }),
427 Err(..) if outside_mods_empty => Err(ModuleResolutionError {
428 module: mod_name.to_string(),
429 kind: ModuleResolutionErrorKind::NotFound { file: file_path },
430 }),
431 Err(..) => {
432 if should_insert {
433 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
434 }
435 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
436 }
437 }
438 }
439 Err(mod_err) if !mods_outside_ast.is_empty() => {
440 if let ModError::ParserError(e) = mod_err {
441 e.cancel();
442 }
443 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
444 }
445 Err(e) => match e {
446 ModError::FileNotFound(_, default_path, _secondary_path) => {
447 Err(ModuleResolutionError {
448 module: mod_name.to_string(),
449 kind: ModuleResolutionErrorKind::NotFound { file: default_path },
450 })
451 }
452 ModError::MultipleCandidates(_, default_path, secondary_path) => {
453 Err(ModuleResolutionError {
454 module: mod_name.to_string(),
455 kind: ModuleResolutionErrorKind::MultipleCandidates {
456 default_path,
457 secondary_path,
458 },
459 })
460 }
461 ModError::ParserError(_)
462 | ModError::CircularInclusion(_)
463 | ModError::ModInBlock(_) => Err(ModuleResolutionError {
464 module: mod_name.to_string(),
465 kind: ModuleResolutionErrorKind::ParseError {
466 file: self.directory.path.clone(),
467 },
468 }),
469 },
470 }
471 }
472
473 fn push_inline_mod_directory(&mut self, id: symbol::Ident, attrs: &[ast::Attribute]) {
474 if let Some(path) = find_path_value(attrs) {
475 self.directory.path.push(path.as_str());
476 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
477 } else {
478 let id = id.as_str();
479 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
486 if let Some(ident) = relative.take() {
487 self.directory.path.push(ident.as_str());
489
490 if self.directory.path.exists() && !self.directory.path.join(id).exists() {
493 return;
494 }
495 }
496 }
497 self.directory.path.push(id);
498 }
499 }
500
501 fn find_mods_outside_of_ast(
502 &self,
503 attrs: &[ast::Attribute],
504 sub_mod: &Module<'ast>,
505 ) -> Vec<(PathBuf, DirectoryOwnership, Module<'ast>)> {
506 let mut path_visitor = visitor::PathVisitor::default();
508 for attr in attrs.iter() {
509 if let Some(meta) = attr.meta() {
510 path_visitor.visit_meta_item(&meta)
511 }
512 }
513 let mut result = vec![];
514 for path in path_visitor.paths() {
515 let mut actual_path = self.directory.path.clone();
516 actual_path.push(&path);
517 if !actual_path.exists() {
518 continue;
519 }
520 if self.psess.is_file_parsed(&actual_path) {
521 result.push((
523 actual_path,
524 DirectoryOwnership::Owned { relative: None },
525 sub_mod.clone(),
526 ));
527 continue;
528 }
529 let (attrs, items, span) =
530 match Parser::parse_file_as_module(self.psess, &actual_path, sub_mod.span) {
531 Ok((ref attrs, _, _)) if contains_skip(attrs) => continue,
532 Ok(m) => m,
533 Err(..) => continue,
534 };
535
536 result.push((
537 actual_path,
538 DirectoryOwnership::Owned { relative: None },
539 Module::new(
540 span,
541 Some(Cow::Owned(ast::ModKind::Unloaded)),
542 Cow::Owned(items),
543 Cow::Owned(attrs),
544 ),
545 ))
546 }
547 result
548 }
549}
550
551fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
552 if attr.has_name(sym::path) {
553 attr.value_str()
554 } else {
555 None
556 }
557}
558
559fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
563 attrs.iter().flat_map(path_value).next()
564}
565
566fn is_cfg_if(item: &ast::Item) -> bool {
567 match item.kind {
568 ast::ItemKind::MacCall(ref mac) => {
569 if let Some(first_segment) = mac.path.segments.first() {
570 if first_segment.ident.name == Symbol::intern("cfg_if") {
571 return true;
572 }
573 }
574 false
575 }
576 _ => false,
577 }
578}