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 #[derive(Debug, Error)]
85 pub(crate) enum ModuleResolutionErrorKind {
86 /// Find a file that cannot be parsed.
87 #[error("cannot parse {file}")]
88 ParseError { file: PathBuf },
89 /// File cannot be found.
90 #[error("{file} does not exist")]
91 NotFound { file: PathBuf },
95 enum SubModKind<'a, 'ast> {
97 External(PathBuf, DirectoryOwnership, Module<'ast>),
98 /// `mod foo;` with multiple sources.
99 MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
101 Internal(&'a ast::Item),
104 impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
105 /// Creates a new `ModResolver`.
107 parse_sess: &'sess ParseSess,
108 directory_ownership: DirectoryOwnership,
112 directory: Directory {
113 path: PathBuf::new(),
114 ownership: directory_ownership,
116 file_map: BTreeMap::new(),
122 /// Creates a map that maps a file name to the module in AST.
123 pub(crate) fn visit_crate(
125 krate: &'ast ast::Crate,
126 ) -> Result<FileModMap<'ast>, ModuleResolutionError> {
127 let root_filename = self.parse_sess.span_to_filename(krate.span);
128 self.directory.path = match root_filename {
129 FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
133 // Skip visiting sub modules when the input is from stdin.
135 self.visit_mod_from_ast(&krate.items)?;
138 let snippet_provider = self.parse_sess.snippet_provider(krate.span);
140 self.file_map.insert(
143 mk_sp(snippet_provider.start_pos(), snippet_provider.end_pos()),
145 Cow::Borrowed(&krate.items),
146 Cow::Borrowed(&krate.attrs),
152 /// Visit `cfg_if` macro and look for module declarations.
153 fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> {
154 let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess);
155 visitor.visit_item(&item);
156 for module_item in visitor.mods() {
157 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = module_item.item.kind {
161 module_item.item.span,
162 Some(Cow::Owned(sub_mod_kind.clone())),
172 /// Visit modules defined inside macro calls.
173 fn visit_mod_outside_ast(
175 items: Vec<rustc_ast::ptr::P<ast::Item>>,
176 ) -> Result<(), ModuleResolutionError> {
178 if is_cfg_if(&item) {
179 self.visit_cfg_if(Cow::Owned(item.into_inner()))?;
183 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
184 let span = item.span;
189 Some(Cow::Owned(sub_mod_kind.clone())),
199 /// Visit modules from AST.
200 fn visit_mod_from_ast(
202 items: &'ast [rustc_ast::ptr::P<ast::Item>],
203 ) -> Result<(), ModuleResolutionError> {
206 self.visit_cfg_if(Cow::Borrowed(item))?;
209 if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
210 let span = item.span;
215 Some(Cow::Borrowed(sub_mod_kind)),
217 Cow::Borrowed(&item.attrs),
228 sub_mod: Module<'ast>,
229 ) -> Result<(), ModuleResolutionError> {
230 let old_directory = self.directory.clone();
231 let sub_mod_kind = self.peek_sub_mod(item, &sub_mod)?;
232 if let Some(sub_mod_kind) = sub_mod_kind {
233 self.insert_sub_mod(sub_mod_kind.clone())?;
234 self.visit_sub_mod_inner(sub_mod, sub_mod_kind)?;
236 self.directory = old_directory;
240 /// Inspect the given sub-module which we are about to visit and returns its kind.
244 sub_mod: &Module<'ast>,
245 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
246 if contains_skip(&item.attrs) {
250 if is_mod_decl(item) {
252 // Look for an extern file.
253 self.find_external_module(item.ident, &item.attrs, sub_mod)
255 // An internal module (`mod foo { /* ... */ }`);
256 Ok(Some(SubModKind::Internal(item)))
262 sub_mod_kind: SubModKind<'c, 'ast>,
263 ) -> Result<(), ModuleResolutionError> {
265 SubModKind::External(mod_path, _, sub_mod) => {
267 .entry(FileName::Real(mod_path))
270 SubModKind::MultiExternal(mods) => {
271 for (mod_path, _, sub_mod) in mods {
273 .entry(FileName::Real(mod_path))
282 fn visit_sub_mod_inner(
284 sub_mod: Module<'ast>,
285 sub_mod_kind: SubModKind<'c, 'ast>,
286 ) -> Result<(), ModuleResolutionError> {
288 SubModKind::External(mod_path, directory_ownership, sub_mod) => {
289 let directory = Directory {
290 path: mod_path.parent().unwrap().to_path_buf(),
291 ownership: directory_ownership,
293 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))
295 SubModKind::Internal(item) => {
296 self.push_inline_mod_directory(item.ident, &item.attrs);
297 self.visit_sub_mod_after_directory_update(sub_mod, None)
299 SubModKind::MultiExternal(mods) => {
300 for (mod_path, directory_ownership, sub_mod) in mods {
301 let directory = Directory {
302 path: mod_path.parent().unwrap().to_path_buf(),
303 ownership: directory_ownership,
305 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))?;
312 fn visit_sub_mod_after_directory_update(
314 sub_mod: Module<'ast>,
315 directory: Option<Directory>,
316 ) -> Result<(), ModuleResolutionError> {
317 if let Some(directory) = directory {
318 self.directory = directory;
320 match (sub_mod.ast_mod_kind, sub_mod.items) {
321 (Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => {
322 self.visit_mod_from_ast(items)
324 (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => {
325 self.visit_mod_outside_ast(items)
331 /// Find a file path in the filesystem which corresponds to the given module.
332 fn find_external_module(
334 mod_name: symbol::Ident,
335 attrs: &[ast::Attribute],
336 sub_mod: &Module<'ast>,
337 ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
338 let relative = match self.directory.ownership {
339 DirectoryOwnership::Owned { relative } => relative,
340 DirectoryOwnership::UnownedViaBlock => None,
342 if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
343 if self.parse_sess.is_file_parsed(&path) {
346 return match Parser::parse_file_as_module(self.parse_sess, &path, sub_mod.span) {
347 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
348 Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
350 DirectoryOwnership::Owned { relative: None },
353 Some(Cow::Owned(ast::ModKind::Unloaded)),
358 Err(ParserError::ParseError) => Err(ModuleResolutionError {
359 module: mod_name.to_string(),
360 kind: ModuleResolutionErrorKind::ParseError { file: path },
362 Err(..) => Err(ModuleResolutionError {
363 module: mod_name.to_string(),
364 kind: ModuleResolutionErrorKind::NotFound { file: path },
369 // Look for nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
370 let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
374 .default_submod_path(mod_name, relative, &self.directory.path)
376 Ok(ModulePathSuccess {
381 let outside_mods_empty = mods_outside_ast.is_empty();
382 let should_insert = !mods_outside_ast
384 .any(|(outside_path, _, _)| outside_path == &file_path);
385 if self.parse_sess.is_file_parsed(&file_path) {
386 if outside_mods_empty {
390 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
392 return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
395 match Parser::parse_file_as_module(self.parse_sess, &file_path, sub_mod.span) {
396 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
397 Ok((attrs, items, span)) if outside_mods_empty => {
398 Ok(Some(SubModKind::External(
403 Some(Cow::Owned(ast::ModKind::Unloaded)),
409 Ok((attrs, items, span)) => {
410 mods_outside_ast.push((
415 Some(Cow::Owned(ast::ModKind::Unloaded)),
421 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
423 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
425 Err(ParserError::ParseError) => Err(ModuleResolutionError {
426 module: mod_name.to_string(),
427 kind: ModuleResolutionErrorKind::ParseError { file: file_path },
429 Err(..) if outside_mods_empty => Err(ModuleResolutionError {
430 module: mod_name.to_string(),
431 kind: ModuleResolutionErrorKind::NotFound { file: file_path },
435 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
437 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
441 Err(mod_err) if !mods_outside_ast.is_empty() => {
442 if let ModError::ParserError(mut e) = mod_err {
445 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
447 Err(_) => Err(ModuleResolutionError {
448 module: mod_name.to_string(),
449 kind: ModuleResolutionErrorKind::NotFound {
450 file: self.directory.path.clone(),
456 fn push_inline_mod_directory(&mut self, id: symbol::Ident, attrs: &[ast::Attribute]) {
457 if let Some(path) = find_path_value(attrs) {
458 self.directory.path.push(path.as_str());
459 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
461 // We have to push on the current module name in the case of relative
462 // paths in order to ensure that any additional module paths from inline
463 // `mod x { ... }` come after the relative extension.
465 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
466 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
467 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
468 if let Some(ident) = relative.take() {
469 // remove the relative offset
470 self.directory.path.push(ident.as_str());
473 self.directory.path.push(id.as_str());
477 fn find_mods_outside_of_ast(
479 attrs: &[ast::Attribute],
480 sub_mod: &Module<'ast>,
481 ) -> Vec<(PathBuf, DirectoryOwnership, Module<'ast>)> {
482 // Filter nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
483 let mut path_visitor = visitor::PathVisitor::default();
484 for attr in attrs.iter() {
485 if let Some(meta) = attr.meta() {
486 path_visitor.visit_meta_item(&meta)
489 let mut result = vec![];
490 for path in path_visitor.paths() {
491 let mut actual_path = self.directory.path.clone();
492 actual_path.push(&path);
493 if !actual_path.exists() {
496 if self.parse_sess.is_file_parsed(&actual_path) {
497 // If the specified file is already parsed, then we just use that.
500 DirectoryOwnership::Owned { relative: None },
505 let (attrs, items, span) =
506 match Parser::parse_file_as_module(self.parse_sess, &actual_path, sub_mod.span) {
507 Ok((ref attrs, _, _)) if contains_skip(attrs) => continue,
514 DirectoryOwnership::Owned { relative: None },
517 Some(Cow::Owned(ast::ModKind::Unloaded)),
527 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
528 if attr.has_name(sym::path) {
535 // N.B., even when there are multiple `#[path = ...]` attributes, we just need to
536 // examine the first one, since rustc ignores the second and the subsequent ones
537 // as unused attributes.
538 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
539 attrs.iter().flat_map(path_value).next()
542 fn is_cfg_if(item: &ast::Item) -> bool {
544 ast::ItemKind::MacCall(ref mac) => {
545 if let Some(first_segment) = mac.path.segments.first() {
546 if first_segment.ident.name == Symbol::intern("cfg_if") {