]> git.lizzy.rs Git - rust.git/blob - src/modules.rs
In the docs for `hex_literal_case`, show the default as a possible value
[rust.git] / 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::parse::parser::{
16     Directory, DirectoryOwnership, ModError, ModulePathSuccess, Parser, ParserError,
17 };
18 use crate::parse::session::ParseSess;
19 use crate::utils::{contains_skip, mk_sp};
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 /// 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:?}")]
95     MultipleCandidates {
96         default_path: PathBuf,
97         secondary_path: PathBuf,
98     },
99 }
100
101 #[derive(Clone)]
102 enum SubModKind<'a, 'ast> {
103     /// `mod foo;`
104     External(PathBuf, DirectoryOwnership, Module<'ast>),
105     /// `mod foo;` with multiple sources.
106     MultiExternal(Vec<(PathBuf, DirectoryOwnership, Module<'ast>)>),
107     /// `mod foo {}`
108     Internal(&'a ast::Item),
109 }
110
111 impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
112     /// Creates a new `ModResolver`.
113     pub(crate) fn new(
114         parse_sess: &'sess ParseSess,
115         directory_ownership: DirectoryOwnership,
116         recursive: bool,
117     ) -> Self {
118         ModResolver {
119             directory: Directory {
120                 path: PathBuf::new(),
121                 ownership: directory_ownership,
122             },
123             file_map: BTreeMap::new(),
124             parse_sess,
125             recursive,
126         }
127     }
128
129     /// Creates a map that maps a file name to the module in AST.
130     pub(crate) fn visit_crate(
131         mut self,
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(),
137             _ => PathBuf::new(),
138         };
139
140         // Skip visiting sub modules when the input is from stdin.
141         if self.recursive {
142             self.visit_mod_from_ast(&krate.items)?;
143         }
144
145         let snippet_provider = self.parse_sess.snippet_provider(krate.spans.inner_span);
146
147         self.file_map.insert(
148             root_filename,
149             Module::new(
150                 mk_sp(snippet_provider.start_pos(), snippet_provider.end_pos()),
151                 None,
152                 Cow::Borrowed(&krate.items),
153                 Cow::Borrowed(&krate.attrs),
154             ),
155         );
156         Ok(self.file_map)
157     }
158
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 {
165                 self.visit_sub_mod(
166                     &module_item.item,
167                     Module::new(
168                         module_item.item.span,
169                         Some(Cow::Owned(sub_mod_kind.clone())),
170                         Cow::Owned(vec![]),
171                         Cow::Owned(vec![]),
172                     ),
173                 )?;
174             }
175         }
176         Ok(())
177     }
178
179     /// Visit modules defined inside macro calls.
180     fn visit_mod_outside_ast(
181         &mut self,
182         items: Vec<rustc_ast::ptr::P<ast::Item>>,
183     ) -> Result<(), ModuleResolutionError> {
184         for item in items {
185             if is_cfg_if(&item) {
186                 self.visit_cfg_if(Cow::Owned(item.into_inner()))?;
187                 continue;
188             }
189
190             if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
191                 let span = item.span;
192                 self.visit_sub_mod(
193                     &item,
194                     Module::new(
195                         span,
196                         Some(Cow::Owned(sub_mod_kind.clone())),
197                         Cow::Owned(vec![]),
198                         Cow::Owned(vec![]),
199                     ),
200                 )?;
201             }
202         }
203         Ok(())
204     }
205
206     /// Visit modules from AST.
207     fn visit_mod_from_ast(
208         &mut self,
209         items: &'ast [rustc_ast::ptr::P<ast::Item>],
210     ) -> Result<(), ModuleResolutionError> {
211         for item in items {
212             if is_cfg_if(item) {
213                 self.visit_cfg_if(Cow::Borrowed(item))?;
214             }
215
216             if let ast::ItemKind::Mod(_, ref sub_mod_kind) = item.kind {
217                 let span = item.span;
218                 self.visit_sub_mod(
219                     item,
220                     Module::new(
221                         span,
222                         Some(Cow::Borrowed(sub_mod_kind)),
223                         Cow::Owned(vec![]),
224                         Cow::Borrowed(&item.attrs),
225                     ),
226                 )?;
227             }
228         }
229         Ok(())
230     }
231
232     fn visit_sub_mod(
233         &mut self,
234         item: &'c ast::Item,
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)?;
242         }
243         self.directory = old_directory;
244         Ok(())
245     }
246
247     /// Inspect the given sub-module which we are about to visit and returns its kind.
248     fn peek_sub_mod(
249         &self,
250         item: &'c ast::Item,
251         sub_mod: &Module<'ast>,
252     ) -> Result<Option<SubModKind<'c, 'ast>>, ModuleResolutionError> {
253         if contains_skip(&item.attrs) {
254             return Ok(None);
255         }
256
257         if is_mod_decl(item) {
258             // mod foo;
259             // Look for an extern file.
260             self.find_external_module(item.ident, &item.attrs, sub_mod)
261         } else {
262             // An internal module (`mod foo { /* ... */ }`);
263             Ok(Some(SubModKind::Internal(item)))
264         }
265     }
266
267     fn insert_sub_mod(
268         &mut self,
269         sub_mod_kind: SubModKind<'c, 'ast>,
270     ) -> Result<(), ModuleResolutionError> {
271         match sub_mod_kind {
272             SubModKind::External(mod_path, _, sub_mod) => {
273                 self.file_map
274                     .entry(FileName::Real(mod_path))
275                     .or_insert(sub_mod);
276             }
277             SubModKind::MultiExternal(mods) => {
278                 for (mod_path, _, sub_mod) in mods {
279                     self.file_map
280                         .entry(FileName::Real(mod_path))
281                         .or_insert(sub_mod);
282                 }
283             }
284             _ => (),
285         }
286         Ok(())
287     }
288
289     fn visit_sub_mod_inner(
290         &mut self,
291         sub_mod: Module<'ast>,
292         sub_mod_kind: SubModKind<'c, 'ast>,
293     ) -> Result<(), ModuleResolutionError> {
294         match sub_mod_kind {
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,
299                 };
300                 self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))
301             }
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)
305             }
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,
311                     };
312                     self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))?;
313                 }
314                 Ok(())
315             }
316         }
317     }
318
319     fn visit_sub_mod_after_directory_update(
320         &mut self,
321         sub_mod: Module<'ast>,
322         directory: Option<Directory>,
323     ) -> Result<(), ModuleResolutionError> {
324         if let Some(directory) = directory {
325             self.directory = directory;
326         }
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)
330             }
331             (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => {
332                 self.visit_mod_outside_ast(items)
333             }
334             (_, _) => Ok(()),
335         }
336     }
337
338     /// Find a file path in the filesystem which corresponds to the given module.
339     fn find_external_module(
340         &self,
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,
348         };
349         if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) {
350             if self.parse_sess.is_file_parsed(&path) {
351                 return Ok(None);
352             }
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(
356                     path,
357                     DirectoryOwnership::Owned { relative: None },
358                     Module::new(
359                         span,
360                         Some(Cow::Owned(ast::ModKind::Unloaded)),
361                         Cow::Owned(items),
362                         Cow::Owned(attrs),
363                     ),
364                 ))),
365                 Err(ParserError::ParseError) => Err(ModuleResolutionError {
366                     module: mod_name.to_string(),
367                     kind: ModuleResolutionErrorKind::ParseError { file: path },
368                 }),
369                 Err(..) => Err(ModuleResolutionError {
370                     module: mod_name.to_string(),
371                     kind: ModuleResolutionErrorKind::NotFound { file: path },
372                 }),
373             };
374         }
375
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);
378
379         match self
380             .parse_sess
381             .default_submod_path(mod_name, relative, &self.directory.path)
382         {
383             Ok(ModulePathSuccess {
384                 file_path,
385                 dir_ownership,
386                 ..
387             }) => {
388                 let outside_mods_empty = mods_outside_ast.is_empty();
389                 let should_insert = !mods_outside_ast
390                     .iter()
391                     .any(|(outside_path, _, _)| outside_path == &file_path);
392                 if self.parse_sess.is_file_parsed(&file_path) {
393                     if outside_mods_empty {
394                         return Ok(None);
395                     } else {
396                         if should_insert {
397                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
398                         }
399                         return Ok(Some(SubModKind::MultiExternal(mods_outside_ast)));
400                     }
401                 }
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(
406                             file_path,
407                             dir_ownership,
408                             Module::new(
409                                 span,
410                                 Some(Cow::Owned(ast::ModKind::Unloaded)),
411                                 Cow::Owned(items),
412                                 Cow::Owned(attrs),
413                             ),
414                         )))
415                     }
416                     Ok((attrs, items, span)) => {
417                         mods_outside_ast.push((
418                             file_path.clone(),
419                             dir_ownership,
420                             Module::new(
421                                 span,
422                                 Some(Cow::Owned(ast::ModKind::Unloaded)),
423                                 Cow::Owned(items),
424                                 Cow::Owned(attrs),
425                             ),
426                         ));
427                         if should_insert {
428                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
429                         }
430                         Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
431                     }
432                     Err(ParserError::ParseError) => Err(ModuleResolutionError {
433                         module: mod_name.to_string(),
434                         kind: ModuleResolutionErrorKind::ParseError { file: file_path },
435                     }),
436                     Err(..) if outside_mods_empty => Err(ModuleResolutionError {
437                         module: mod_name.to_string(),
438                         kind: ModuleResolutionErrorKind::NotFound { file: file_path },
439                     }),
440                     Err(..) => {
441                         if should_insert {
442                             mods_outside_ast.push((file_path, dir_ownership, sub_mod.clone()));
443                         }
444                         Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
445                     }
446                 }
447             }
448             Err(mod_err) if !mods_outside_ast.is_empty() => {
449                 if let ModError::ParserError(e) = mod_err {
450                     e.cancel();
451                 }
452                 Ok(Some(SubModKind::MultiExternal(mods_outside_ast)))
453             }
454             Err(e) => match e {
455                 ModError::FileNotFound(_, default_path, _secondary_path) => {
456                     Err(ModuleResolutionError {
457                         module: mod_name.to_string(),
458                         kind: ModuleResolutionErrorKind::NotFound { file: default_path },
459                     })
460                 }
461                 ModError::MultipleCandidates(_, default_path, secondary_path) => {
462                     Err(ModuleResolutionError {
463                         module: mod_name.to_string(),
464                         kind: ModuleResolutionErrorKind::MultipleCandidates {
465                             default_path,
466                             secondary_path,
467                         },
468                     })
469                 }
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(),
476                     },
477                 }),
478             },
479         }
480     }
481
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 };
486         } else {
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.
491             //
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());
498
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() {
502                         return;
503                     }
504                 }
505             }
506             self.directory.path.push(id);
507         }
508     }
509
510     fn find_mods_outside_of_ast(
511         &self,
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)
520             }
521         }
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() {
527                 continue;
528             }
529             if self.parse_sess.is_file_parsed(&actual_path) {
530                 // If the specified file is already parsed, then we just use that.
531                 result.push((
532                     actual_path,
533                     DirectoryOwnership::Owned { relative: None },
534                     sub_mod.clone(),
535                 ));
536                 continue;
537             }
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,
541                     Ok(m) => m,
542                     Err(..) => continue,
543                 };
544
545             result.push((
546                 actual_path,
547                 DirectoryOwnership::Owned { relative: None },
548                 Module::new(
549                     span,
550                     Some(Cow::Owned(ast::ModKind::Unloaded)),
551                     Cow::Owned(items),
552                     Cow::Owned(attrs),
553                 ),
554             ))
555         }
556         result
557     }
558 }
559
560 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
561     if attr.has_name(sym::path) {
562         attr.value_str()
563     } else {
564         None
565     }
566 }
567
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()
573 }
574
575 fn is_cfg_if(item: &ast::Item) -> bool {
576     match item.kind {
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") {
580                     return true;
581                 }
582             }
583             false
584         }
585         _ => false,
586     }
587 }