]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/modules.rs
Rollup merge of #85223 - simbleau:master, r=steveklabnik
[rust.git] / src / tools / rustfmt / src / modules.rs
1 use std::borrow::Cow;
2 use std::collections::BTreeMap;
3 use std::path::{Path, PathBuf};
4
5 use rustc_ast::ast;
6 use rustc_ast::visit::Visitor;
7 use rustc_ast::AstLike;
8 use rustc_span::symbol::{self, sym, Symbol};
9 use rustc_span::Span;
10 use thiserror::Error;
11
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,
17 };
18 use crate::syntux::session::ParseSess;
19 use crate::utils::contains_skip;
20
21 mod visitor;
22
23 type FileModMap<'ast> = BTreeMap<FileName, Module<'ast>>;
24
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,
32 }
33
34 impl<'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, Vec<rustc_ast::ptr::P<ast::Item>>>,
39         mod_attrs: Cow<'a, Vec<ast::Attribute>>,
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
55 impl<'a> AstLike for Module<'a> {
56     const SUPPORTS_CUSTOM_INNER_ATTRS: bool = true;
57     fn attrs(&self) -> &[ast::Attribute] {
58         &self.inner_attr
59     }
60     fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec<ast::Attribute>)) {
61         f(&mut self.inner_attr)
62     }
63     fn tokens_mut(&mut self) -> Option<&mut Option<rustc_ast::tokenstream::LazyTokenStream>> {
64         unimplemented!()
65     }
66 }
67
68 /// Maps each module to the corresponding file.
69 pub(crate) struct ModResolver<'ast, 'sess> {
70     parse_sess: &'sess ParseSess,
71     directory: Directory,
72     file_map: FileModMap<'ast>,
73     recursive: bool,
74 }
75
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,
82 }
83
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 },
92 }
93
94 #[derive(Clone)]
95 enum SubModKind<'a, 'ast> {
96     /// `mod foo;`
97     External(PathBuf, DirectoryOwnership, Module<'ast>),
98     /// `mod foo;` with multiple sources.
99     MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
100     /// `mod foo {}`
101     Internal(&'a ast::Item),
102 }
103
104 impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
105     /// Creates a new `ModResolver`.
106     pub(crate) fn new(
107         parse_sess: &'sess ParseSess,
108         directory_ownership: DirectoryOwnership,
109         recursive: bool,
110     ) -> Self {
111         ModResolver {
112             directory: Directory {
113                 path: PathBuf::new(),
114                 ownership: directory_ownership,
115             },
116             file_map: BTreeMap::new(),
117             parse_sess,
118             recursive,
119         }
120     }
121
122     /// Creates a map that maps a file name to the module in AST.
123     pub(crate) fn visit_crate(
124         mut self,
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(),
130             _ => PathBuf::new(),
131         };
132
133         // Skip visiting sub modules when the input is from stdin.
134         if self.recursive {
135             self.visit_mod_from_ast(&krate.items)?;
136         }
137
138         self.file_map.insert(
139             root_filename,
140             Module::new(
141                 krate.span,
142                 None,
143                 Cow::Borrowed(&krate.items),
144                 Cow::Borrowed(&krate.attrs),
145             ),
146         );
147         Ok(self.file_map)
148     }
149
150     /// Visit `cfg_if` macro and look for module declarations.
151     fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> {
152         let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess);
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(vec![]),
162                         Cow::Owned(vec![]),
163                     ),
164                 )?;
165             }
166         }
167         Ok(())
168     }
169
170     /// Visit modules defined inside macro calls.
171     fn visit_mod_outside_ast(
172         &mut self,
173         items: Vec<rustc_ast::ptr::P<ast::Item>>,
174     ) -> Result<(), ModuleResolutionError> {
175         for item in items {
176             if is_cfg_if(&item) {
177                 self.visit_cfg_if(Cow::Owned(item.into_inner()))?;
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(vec![]),
189                         Cow::Owned(vec![]),
190                     ),
191                 )?;
192             }
193         }
194         Ok(())
195     }
196
197     /// Visit modules from AST.
198     fn visit_mod_from_ast(
199         &mut self,
200         items: &'ast Vec<rustc_ast::ptr::P<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(vec![]),
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     /// Inspect the given sub-module which we are about to visit and returns its kind.
239     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             // mod foo;
250             // Look for an extern file.
251             self.find_external_module(item.ident, &item.attrs, sub_mod)
252         } else {
253             // An internal module (`mod foo { /* ... */ }`);
254             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(ref item) => {
294                 self.push_inline_mod_directory(item.ident, &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(..)), Cow::Owned(items)) => self.visit_mod_outside_ast(items),
323             (_, _) => Ok(()),
324         }
325     }
326
327     /// Find a file path in the filesystem which corresponds to the given module.
328     fn find_external_module(
329         &self,
330         mod_name: symbol::Ident,
331         attrs: &[ast::Attribute],
332         sub_mod: &Module<'ast>,
333     ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
334         let relative = match self.directory.ownership {
335             DirectoryOwnership::Owned { relative } => relative,
336             DirectoryOwnership::UnownedViaBlock => None,
337         };
338         if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
339             if self.parse_sess.is_file_parsed(&path) {
340                 return Ok(None);
341             }
342             return match Parser::parse_file_as_module(self.parse_sess, &path, sub_mod.span) {
343                 Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
344                 Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
345                     path,
346                     DirectoryOwnership::Owned { relative: None },
347                     Module::new(
348                         span,
349                         Some(Cow::Owned(ast::ModKind::Unloaded)),
350                         Cow::Owned(items),
351                         Cow::Owned(attrs),
352                     ),
353                 ))),
354                 Err(ParserError::ParseError) => Err(ModuleResolutionError {
355                     module: mod_name.to_string(),
356                     kind: ModuleResolutionErrorKind::ParseError { file: path },
357                 }),
358                 Err(..) => Err(ModuleResolutionError {
359                     module: mod_name.to_string(),
360                     kind: ModuleResolutionErrorKind::NotFound { file: path },
361                 }),
362             };
363         }
364
365         // Look for nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
366         let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
367
368         match self
369             .parse_sess
370             .default_submod_path(mod_name, relative, &self.directory.path)
371         {
372             Ok(ModulePathSuccess {
373                 file_path,
374                 dir_ownership,
375                 ..
376             }) => {
377                 let outside_mods_empty = mods_outside_ast.is_empty();
378                 let should_insert = !mods_outside_ast
379                     .iter()
380                     .any(|(outside_path, _, _)| outside_path == &file_path);
381                 if self.parse_sess.is_file_parsed(&file_path) {
382                     if outside_mods_empty {
383                         return Ok(None);
384                     } else {
385                         if should_insert {
386                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
387                         }
388                         return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
389                     }
390                 }
391                 match Parser::parse_file_as_module(self.parse_sess, &file_path, sub_mod.span) {
392                     Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
393                     Ok((attrs, items, span)) if outside_mods_empty => {
394                         Ok(Some(SubModKind::External(
395                             file_path,
396                             dir_ownership,
397                             Module::new(
398                                 span,
399                                 Some(Cow::Owned(ast::ModKind::Unloaded)),
400                                 Cow::Owned(items),
401                                 Cow::Owned(attrs),
402                             ),
403                         )))
404                     }
405                     Ok((attrs, items, span)) => {
406                         mods_outside_ast.push((
407                             file_path.clone(),
408                             dir_ownership,
409                             Module::new(
410                                 span,
411                                 Some(Cow::Owned(ast::ModKind::Unloaded)),
412                                 Cow::Owned(items),
413                                 Cow::Owned(attrs),
414                             ),
415                         ));
416                         if should_insert {
417                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
418                         }
419                         Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
420                     }
421                     Err(ParserError::ParseError) => Err(ModuleResolutionError {
422                         module: mod_name.to_string(),
423                         kind: ModuleResolutionErrorKind::ParseError { file: file_path },
424                     }),
425                     Err(..) if outside_mods_empty => Err(ModuleResolutionError {
426                         module: mod_name.to_string(),
427                         kind: ModuleResolutionErrorKind::NotFound { file: file_path },
428                     }),
429                     Err(..) => {
430                         if should_insert {
431                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
432                         }
433                         Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
434                     }
435                 }
436             }
437             Err(mod_err) if !mods_outside_ast.is_empty() => {
438                 if let ModError::ParserError(mut e) = mod_err {
439                     e.cancel();
440                 }
441                 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
442             }
443             Err(_) => Err(ModuleResolutionError {
444                 module: mod_name.to_string(),
445                 kind: ModuleResolutionErrorKind::NotFound {
446                     file: self.directory.path.clone(),
447                 },
448             }),
449         }
450     }
451
452     fn push_inline_mod_directory(&mut self, id: symbol::Ident, attrs: &[ast::Attribute]) {
453         if let Some(path) = find_path_value(attrs) {
454             self.directory.path.push(&*path.as_str());
455             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
456         } else {
457             // We have to push on the current module name in the case of relative
458             // paths in order to ensure that any additional module paths from inline
459             // `mod x { ... }` come after the relative extension.
460             //
461             // For example, a `mod z { ... }` inside `x/y.rs` should set the current
462             // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
463             if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
464                 if let Some(ident) = relative.take() {
465                     // remove the relative offset
466                     self.directory.path.push(&*ident.as_str());
467                 }
468             }
469             self.directory.path.push(&*id.as_str());
470         }
471     }
472
473     fn find_mods_outside_of_ast(
474         &self,
475         attrs: &[ast::Attribute],
476         sub_mod: &Module<'ast>,
477     ) -> Vec<(PathBuf, DirectoryOwnership, Module<'ast>)> {
478         // Filter nested path, like `#[cfg_attr(feature = "foo", path = "bar.rs")]`.
479         let mut path_visitor = visitor::PathVisitor::default();
480         for attr in attrs.iter() {
481             if let Some(meta) = attr.meta() {
482                 path_visitor.visit_meta_item(&meta)
483             }
484         }
485         let mut result = vec![];
486         for path in path_visitor.paths() {
487             let mut actual_path = self.directory.path.clone();
488             actual_path.push(&path);
489             if !actual_path.exists() {
490                 continue;
491             }
492             if self.parse_sess.is_file_parsed(&actual_path) {
493                 // If the specified file is already parsed, then we just use that.
494                 result.push((
495                     actual_path,
496                     DirectoryOwnership::Owned { relative: None },
497                     sub_mod.clone(),
498                 ));
499                 continue;
500             }
501             let (attrs, items, span) =
502                 match Parser::parse_file_as_module(self.parse_sess, &actual_path, sub_mod.span) {
503                     Ok((ref attrs, _, _)) if contains_skip(attrs) => continue,
504                     Ok(m) => m,
505                     Err(..) => continue,
506                 };
507
508             result.push((
509                 actual_path,
510                 DirectoryOwnership::Owned { relative: None },
511                 Module::new(
512                     span,
513                     Some(Cow::Owned(ast::ModKind::Unloaded)),
514                     Cow::Owned(items),
515                     Cow::Owned(attrs),
516                 ),
517             ))
518         }
519         result
520     }
521 }
522
523 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
524     if attr.has_name(sym::path) {
525         attr.value_str()
526     } else {
527         None
528     }
529 }
530
531 // N.B., even when there are multiple `#[path = ...]` attributes, we just need to
532 // examine the first one, since rustc ignores the second and the subsequent ones
533 // as unused attributes.
534 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
535     attrs.iter().flat_map(path_value).next()
536 }
537
538 fn is_cfg_if(item: &ast::Item) -> bool {
539     match item.kind {
540         ast::ItemKind::MacCall(ref mac) => {
541             if let Some(first_segment) = mac.path.segments.first() {
542                 if first_segment.ident.name == Symbol::intern("cfg_if") {
543                     return true;
544                 }
545             }
546             false
547         }
548         _ => false,
549     }
550 }