2 use std::collections::BTreeMap;
3 use std::path::{Path, PathBuf};
6 use rustc_ast::visit::Visitor;
7 use rustc_ast::AstLike;
8 use rustc_span::symbol::{self, sym, Symbol};
12 use crate::attr::MetaVisitor;
13 use crate::config::FileName;
14 use crate::items::is_mod_decl;
15 use crate::parse::parser::{
16 Directory, DirectoryOwnership, ModError, ModulePathSuccess, Parser, ParserError,
18 use crate::parse::session::ParseSess;
19 use crate::utils::{contains_skip, mk_sp};
23 type FileModMap<'ast> = BTreeMap<FileName, Module<'ast>>;
25 /// Represents module with its inner attributes.
26 #[derive(Debug, Clone)]
27 pub(crate) struct Module<'a> {
28 ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
29 pub(crate) items: Cow<'a, Vec<rustc_ast::ptr::P<ast::Item>>>,
30 inner_attr: Vec<ast::Attribute>,
31 pub(crate) span: Span,
37 ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
38 mod_items: Cow<'a, Vec<rustc_ast::ptr::P<ast::Item>>>,
39 mod_attrs: Cow<'a, Vec<ast::Attribute>>,
41 let inner_attr = mod_attrs
43 .filter(|attr| attr.style == ast::AttrStyle::Inner)
55 impl<'a> AstLike for Module<'a> {
56 const SUPPORTS_CUSTOM_INNER_ATTRS: bool = true;
57 fn attrs(&self) -> &[ast::Attribute] {
60 fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<ast::Attribute>)) {
61 f(&mut self.inner_attr)
63 fn tokens_mut(&mut self) -> Option<&mut Option<rustc_ast::tokenstream::LazyTokenStream>> {
68 /// Maps each module to the corresponding file.
69 pub(crate) struct ModResolver<'ast, 'sess> {
70 parse_sess: &'sess ParseSess,
72 file_map: FileModMap<'ast>,
76 /// Represents errors while trying to resolve modules.
77 #[derive(Debug, Error)]
78 #[error("failed to resolve mod `{module}`: {kind}")]
79 pub struct ModuleResolutionError {
80 pub(crate) module: String,
81 pub(crate) kind: ModuleResolutionErrorKind,
84 /// Defines variants similar to those of [rustc_expand::module::ModError]
85 #[derive(Debug, Error)]
86 pub(crate) enum ModuleResolutionErrorKind {
87 /// Find a file that cannot be parsed.
88 #[error("cannot parse {file}")]
89 ParseError { file: PathBuf },
90 /// File cannot be found.
91 #[error("{file} does not exist")]
92 NotFound { file: PathBuf },
93 /// File a.rs and a/mod.rs both exist
94 #[error("file for module found at both {default_path:?} and {secondary_path:?}")]
96 default_path: PathBuf,
97 secondary_path: PathBuf,
102 enum SubModKind<'a, 'ast> {
104 External(PathBuf, DirectoryOwnership, Module<'ast>),
105 /// `mod foo;` with multiple sources.
106 MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
108 Internal(&'a ast::Item),
111 impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
112 /// Creates a new `ModResolver`.
114 parse_sess: &'sess ParseSess,
115 directory_ownership: DirectoryOwnership,
119 directory: Directory {
120 path: PathBuf::new(),
121 ownership: directory_ownership,
123 file_map: BTreeMap::new(),
129 /// Creates a map that maps a file name to the module in AST.
130 pub(crate) fn visit_crate(
132 krate: &'ast ast::Crate,
133 ) -> Result<FileModMap<'ast>, ModuleResolutionError> {
134 let root_filename = self.parse_sess.span_to_filename(krate.spans.inner_span);
135 self.directory.path = match root_filename {
136 FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
140 // Skip visiting sub modules when the input is from stdin.
142 self.visit_mod_from_ast(&krate.items)?;
145 let snippet_provider = self.parse_sess.snippet_provider(krate.spans.inner_span);
147 self.file_map.insert(
150 mk_sp(snippet_provider.start_pos(), snippet_provider.end_pos()),
152 Cow::Borrowed(&krate.items),
153 Cow::Borrowed(&krate.attrs),
159 /// Visit `cfg_if` macro and look for module declarations.
160 fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> {
161 let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess);
162 visitor.visit_item(&item);
163 for module_item in visitor.mods() {
164 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = module_item.item.kind {
168 module_item.item.span,
169 Some(Cow::Owned(sub_mod_kind.clone())),
179 /// Visit modules defined inside macro calls.
180 fn visit_mod_outside_ast(
182 items: Vec<rustc_ast::ptr::P<ast::Item>>,
183 ) -> Result<(), ModuleResolutionError> {
185 if is_cfg_if(&item) {
186 self.visit_cfg_if(Cow::Owned(item.into_inner()))?;
190 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
191 let span = item.span;
196 Some(Cow::Owned(sub_mod_kind.clone())),
206 /// Visit modules from AST.
207 fn visit_mod_from_ast(
209 items: &'ast [rustc_ast::ptr::P<ast::Item>],
210 ) -> Result<(), ModuleResolutionError> {
213 self.visit_cfg_if(Cow::Borrowed(item))?;
216 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
217 let span = item.span;
222 Some(Cow::Borrowed(sub_mod_kind)),
224 Cow::Borrowed(&item.attrs),
235 sub_mod: Module<'ast>,
236 ) -> Result<(), ModuleResolutionError> {
237 let old_directory = self.directory.clone();
238 let sub_mod_kind = self.peek_sub_mod(item, &sub_mod)?;
239 if let Some(sub_mod_kind) = sub_mod_kind {
240 self.insert_sub_mod(sub_mod_kind.clone())?;
241 self.visit_sub_mod_inner(sub_mod, sub_mod_kind)?;
243 self.directory = old_directory;
247 /// Inspect the given sub-module which we are about to visit and returns its kind.
251 sub_mod: &Module<'ast>,
252 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
253 if contains_skip(&item.attrs) {
257 if is_mod_decl(item) {
259 // Look for an extern file.
260 self.find_external_module(item.ident, &item.attrs, sub_mod)
262 // An internal module (`mod foo { /* ... */ }`);
263 Ok(Some(SubModKind::Internal(item)))
269 sub_mod_kind: SubModKind<'c, 'ast>,
270 ) -> Result<(), ModuleResolutionError> {
272 SubModKind::External(mod_path, _, sub_mod) => {
274 .entry(FileName::Real(mod_path))
277 SubModKind::MultiExternal(mods) => {
278 for (mod_path, _, sub_mod) in mods {
280 .entry(FileName::Real(mod_path))
289 fn visit_sub_mod_inner(
291 sub_mod: Module<'ast>,
292 sub_mod_kind: SubModKind<'c, 'ast>,
293 ) -> Result<(), ModuleResolutionError> {
295 SubModKind::External(mod_path, directory_ownership, sub_mod) => {
296 let directory = Directory {
297 path: mod_path.parent().unwrap().to_path_buf(),
298 ownership: directory_ownership,
300 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))
302 SubModKind::Internal(item) => {
303 self.push_inline_mod_directory(item.ident, &item.attrs);
304 self.visit_sub_mod_after_directory_update(sub_mod, None)
306 SubModKind::MultiExternal(mods) => {
307 for (mod_path, directory_ownership, sub_mod) in mods {
308 let directory = Directory {
309 path: mod_path.parent().unwrap().to_path_buf(),
310 ownership: directory_ownership,
312 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))?;
319 fn visit_sub_mod_after_directory_update(
321 sub_mod: Module<'ast>,
322 directory: Option<Directory>,
323 ) -> Result<(), ModuleResolutionError> {
324 if let Some(directory) = directory {
325 self.directory = directory;
327 match (sub_mod.ast_mod_kind, sub_mod.items) {
328 (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => {
329 self.visit_mod_from_ast(items)
331 (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => {
332 self.visit_mod_outside_ast(items)
338 /// Find a file path in the filesystem which corresponds to the given module.
339 fn find_external_module(
341 mod_name: symbol::Ident,
342 attrs: &[ast::Attribute],
343 sub_mod: &Module<'ast>,
344 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
345 let relative = match self.directory.ownership {
346 DirectoryOwnership::Owned { relative } => relative,
347 DirectoryOwnership::UnownedViaBlock => None,
349 if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
350 if self.parse_sess.is_file_parsed(&path) {
353 return match Parser::parse_file_as_module(self.parse_sess, &path, sub_mod.span) {
354 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
355 Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
357 DirectoryOwnership::Owned { relative: None },
360 Some(Cow::Owned(ast::ModKind::Unloaded)),
365 Err(ParserError::ParseError) => Err(ModuleResolutionError {
366 module: mod_name.to_string(),
367 kind: ModuleResolutionErrorKind::ParseError { file: path },
369 Err(..) => Err(ModuleResolutionError {
370 module: mod_name.to_string(),
371 kind: ModuleResolutionErrorKind::NotFound { file: path },
376 // Look for nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
377 let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
381 .default_submod_path(mod_name, relative, &self.directory.path)
383 Ok(ModulePathSuccess {
388 let outside_mods_empty = mods_outside_ast.is_empty();
389 let should_insert = !mods_outside_ast
391 .any(|(outside_path, _, _)| outside_path == &file_path);
392 if self.parse_sess.is_file_parsed(&file_path) {
393 if outside_mods_empty {
397 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
399 return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
402 match Parser::parse_file_as_module(self.parse_sess, &file_path, sub_mod.span) {
403 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
404 Ok((attrs, items, span)) if outside_mods_empty => {
405 Ok(Some(SubModKind::External(
410 Some(Cow::Owned(ast::ModKind::Unloaded)),
416 Ok((attrs, items, span)) => {
417 mods_outside_ast.push((
422 Some(Cow::Owned(ast::ModKind::Unloaded)),
428 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
430 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
432 Err(ParserError::ParseError) => Err(ModuleResolutionError {
433 module: mod_name.to_string(),
434 kind: ModuleResolutionErrorKind::ParseError { file: file_path },
436 Err(..) if outside_mods_empty => Err(ModuleResolutionError {
437 module: mod_name.to_string(),
438 kind: ModuleResolutionErrorKind::NotFound { file: file_path },
442 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
444 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
448 Err(mod_err) if !mods_outside_ast.is_empty() => {
449 if let ModError::ParserError(e) = mod_err {
452 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
455 ModError::FileNotFound(_, default_path, _secondary_path) => {
456 Err(ModuleResolutionError {
457 module: mod_name.to_string(),
458 kind: ModuleResolutionErrorKind::NotFound { file: default_path },
461 ModError::MultipleCandidates(_, default_path, secondary_path) => {
462 Err(ModuleResolutionError {
463 module: mod_name.to_string(),
464 kind: ModuleResolutionErrorKind::MultipleCandidates {
470 ModError::ParserError(_)
471 | ModError::CircularInclusion(_)
472 | ModError::ModInBlock(_) => Err(ModuleResolutionError {
473 module: mod_name.to_string(),
474 kind: ModuleResolutionErrorKind::ParseError {
475 file: self.directory.path.clone(),
482 fn push_inline_mod_directory(&mut self, id: symbol::Ident, attrs: &[ast::Attribute]) {
483 if let Some(path) = find_path_value(attrs) {
484 self.directory.path.push(path.as_str());
485 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
487 let id = id.as_str();
488 // We have to push on the current module name in the case of relative
489 // paths in order to ensure that any additional module paths from inline
490 // `mod x { ... }` come after the relative extension.
492 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
493 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
494 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
495 if let Some(ident) = relative.take() {
496 // remove the relative offset
497 self.directory.path.push(ident.as_str());
499 // In the case where there is an x.rs and an ./x directory we want
500 // to prevent adding x twice. For example, ./x/x
501 if self.directory.path.exists() && !self.directory.path.join(id).exists() {
506 self.directory.path.push(id);
510 fn find_mods_outside_of_ast(
512 attrs: &[ast::Attribute],
513 sub_mod: &Module<'ast>,
514 ) -> Vec<(PathBuf, DirectoryOwnership, Module<'ast>)> {
515 // Filter nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
516 let mut path_visitor = visitor::PathVisitor::default();
517 for attr in attrs.iter() {
518 if let Some(meta) = attr.meta() {
519 path_visitor.visit_meta_item(&meta)
522 let mut result = vec![];
523 for path in path_visitor.paths() {
524 let mut actual_path = self.directory.path.clone();
525 actual_path.push(&path);
526 if !actual_path.exists() {
529 if self.parse_sess.is_file_parsed(&actual_path) {
530 // If the specified file is already parsed, then we just use that.
533 DirectoryOwnership::Owned { relative: None },
538 let (attrs, items, span) =
539 match Parser::parse_file_as_module(self.parse_sess, &actual_path, sub_mod.span) {
540 Ok((ref attrs, _, _)) if contains_skip(attrs) => continue,
547 DirectoryOwnership::Owned { relative: None },
550 Some(Cow::Owned(ast::ModKind::Unloaded)),
560 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
561 if attr.has_name(sym::path) {
568 // N.B., even when there are multiple `#[path = ...]` attributes, we just need to
569 // examine the first one, since rustc ignores the second and the subsequent ones
570 // as unused attributes.
571 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
572 attrs.iter().flat_map(path_value).next()
575 fn is_cfg_if(item: &ast::Item) -> bool {
577 ast::ItemKind::MacCall(ref mac) => {
578 if let Some(first_segment) = mac.path.segments.first() {
579 if first_segment.ident.name == Symbol::intern("cfg_if") {