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::syntux::parser::{
16 Directory, DirectoryOwnership, ModError, ModulePathSuccess, Parser, ParserError,
18 use crate::syntux::session::ParseSess;
19 use crate::utils::contains_skip;
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 attrs: Cow<'a, Vec<ast::Attribute>>,
31 inner_attr: Vec<ast::Attribute>,
32 pub(crate) span: Span,
38 ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
39 mod_items: Cow<'a, Vec<rustc_ast::ptr::P<ast::Item>>>,
40 mod_attrs: Cow<'a, Vec<ast::Attribute>>,
42 let inner_attr = mod_attrs
44 .filter(|attr| attr.style == ast::AttrStyle::Inner)
57 impl<'a> AstLike for Module<'a> {
58 const SUPPORTS_CUSTOM_INNER_ATTRS: bool = true;
59 fn attrs(&self) -> &[ast::Attribute] {
62 fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<ast::Attribute>)) {
63 f(&mut self.inner_attr)
65 fn tokens_mut(&mut self) -> Option<&mut Option<rustc_ast::tokenstream::LazyTokenStream>> {
70 /// Maps each module to the corresponding file.
71 pub(crate) struct ModResolver<'ast, 'sess> {
72 parse_sess: &'sess ParseSess,
74 file_map: FileModMap<'ast>,
78 /// Represents errors while trying to resolve modules.
79 #[derive(Debug, Error)]
80 #[error("failed to resolve mod `{module}`: {kind}")]
81 pub struct ModuleResolutionError {
82 pub(crate) module: String,
83 pub(crate) kind: ModuleResolutionErrorKind,
86 #[derive(Debug, Error)]
87 pub(crate) enum ModuleResolutionErrorKind {
88 /// Find a file that cannot be parsed.
89 #[error("cannot parse {file}")]
90 ParseError { file: PathBuf },
91 /// File cannot be found.
92 #[error("{file} does not exist")]
93 NotFound { file: PathBuf },
97 enum SubModKind<'a, 'ast> {
99 External(PathBuf, DirectoryOwnership, Module<'ast>),
100 /// `mod foo;` with multiple sources.
101 MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
103 Internal(&'a ast::Item),
106 impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
107 /// Creates a new `ModResolver`.
109 parse_sess: &'sess ParseSess,
110 directory_ownership: DirectoryOwnership,
114 directory: Directory {
115 path: PathBuf::new(),
116 ownership: directory_ownership,
118 file_map: BTreeMap::new(),
124 /// Creates a map that maps a file name to the module in AST.
125 pub(crate) fn visit_crate(
127 krate: &'ast ast::Crate,
128 ) -> Result<FileModMap<'ast>, ModuleResolutionError> {
129 let root_filename = self.parse_sess.span_to_filename(krate.span);
130 self.directory.path = match root_filename {
131 FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
135 // Skip visiting sub modules when the input is from stdin.
137 self.visit_mod_from_ast(&krate.items)?;
140 self.file_map.insert(
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 Vec<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(ref 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(..)), Cow::Owned(items)) => self.visit_mod_outside_ast(items),
329 /// Find a file path in the filesystem which corresponds to the given module.
330 fn find_external_module(
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,
340 if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
341 if self.parse_sess.is_file_parsed(&path) {
344 return match Parser::parse_file_as_module(self.parse_sess, &path, sub_mod.span) {
345 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
346 Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
348 DirectoryOwnership::Owned { relative: None },
351 Some(Cow::Owned(ast::ModKind::Unloaded)),
356 Err(ParserError::ParseError) => Err(ModuleResolutionError {
357 module: mod_name.to_string(),
358 kind: ModuleResolutionErrorKind::ParseError { file: path },
360 Err(..) => Err(ModuleResolutionError {
361 module: mod_name.to_string(),
362 kind: ModuleResolutionErrorKind::NotFound { file: path },
367 // Look for nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
368 let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
372 .default_submod_path(mod_name, relative, &self.directory.path)
374 Ok(ModulePathSuccess {
379 let outside_mods_empty = mods_outside_ast.is_empty();
380 let should_insert = !mods_outside_ast
382 .any(|(outside_path, _, _)| outside_path == &file_path);
383 if self.parse_sess.is_file_parsed(&file_path) {
384 if outside_mods_empty {
388 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
390 return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
393 match Parser::parse_file_as_module(self.parse_sess, &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(
401 Some(Cow::Owned(ast::ModKind::Unloaded)),
407 Ok((attrs, items, span)) => {
408 mods_outside_ast.push((
413 Some(Cow::Owned(ast::ModKind::Unloaded)),
419 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
421 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
423 Err(ParserError::ParseError) => Err(ModuleResolutionError {
424 module: mod_name.to_string(),
425 kind: ModuleResolutionErrorKind::ParseError { file: file_path },
427 Err(..) if outside_mods_empty => Err(ModuleResolutionError {
428 module: mod_name.to_string(),
429 kind: ModuleResolutionErrorKind::NotFound { file: file_path },
433 mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
435 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
439 Err(mod_err) if !mods_outside_ast.is_empty() => {
440 if let ModError::ParserError(mut e) = mod_err {
443 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
445 Err(_) => Err(ModuleResolutionError {
446 module: mod_name.to_string(),
447 kind: ModuleResolutionErrorKind::NotFound {
448 file: self.directory.path.clone(),
454 fn push_inline_mod_directory(&mut self, id: symbol::Ident, attrs: &[ast::Attribute]) {
455 if let Some(path) = find_path_value(attrs) {
456 self.directory.path.push(&*path.as_str());
457 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
459 // We have to push on the current module name in the case of relative
460 // paths in order to ensure that any additional module paths from inline
461 // `mod x { ... }` come after the relative extension.
463 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
464 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
465 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
466 if let Some(ident) = relative.take() {
467 // remove the relative offset
468 self.directory.path.push(&*ident.as_str());
471 self.directory.path.push(&*id.as_str());
475 fn find_mods_outside_of_ast(
477 attrs: &[ast::Attribute],
478 sub_mod: &Module<'ast>,
479 ) -> Vec<(PathBuf, DirectoryOwnership, Module<'ast>)> {
480 // Filter nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
481 let mut path_visitor = visitor::PathVisitor::default();
482 for attr in attrs.iter() {
483 if let Some(meta) = attr.meta() {
484 path_visitor.visit_meta_item(&meta)
487 let mut result = vec![];
488 for path in path_visitor.paths() {
489 let mut actual_path = self.directory.path.clone();
490 actual_path.push(&path);
491 if !actual_path.exists() {
494 if self.parse_sess.is_file_parsed(&actual_path) {
495 // If the specified file is already parsed, then we just use that.
498 DirectoryOwnership::Owned { relative: None },
503 let (attrs, items, span) =
504 match Parser::parse_file_as_module(self.parse_sess, &actual_path, sub_mod.span) {
505 Ok((ref attrs, _, _)) if contains_skip(attrs) => continue,
512 DirectoryOwnership::Owned { relative: None },
515 Some(Cow::Owned(ast::ModKind::Unloaded)),
525 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
526 if attr.has_name(sym::path) {
533 // N.B., even when there are multiple `#[path = ...]` attributes, we just need to
534 // examine the first one, since rustc ignores the second and the subsequent ones
535 // as unused attributes.
536 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
537 attrs.iter().flat_map(path_value).next()
540 fn is_cfg_if(item: &ast::Item) -> bool {
542 ast::ItemKind::MacCall(ref mac) => {
543 if let Some(first_segment) = mac.path.segments.first() {
544 if first_segment.ident.name == Symbol::intern("cfg_if") {