1 use std::collections::BTreeMap;
3 use std::path::{Path, PathBuf};
6 use syntax::parse::{parser, DirectoryOwnership};
7 use syntax::source_map;
8 use syntax_pos::symbol::Symbol;
10 use crate::config::FileName;
11 use crate::utils::contains_skip;
13 /// List all the files containing modules of a crate.
14 /// If a file is used twice in a crate, it appears only once.
15 pub fn list_files<'a>(
16 krate: &'a ast::Crate,
17 source_map: &source_map::SourceMap,
18 ) -> Result<BTreeMap<FileName, &'a ast::Mod>, io::Error> {
19 let mut result = BTreeMap::new(); // Enforce file order determinism
20 let root_filename = source_map.span_to_filename(krate.span);
22 let parent = match root_filename {
23 source_map::FileName::Real(ref path) => path.parent().unwrap(),
26 list_submodules(&krate.module, parent, None, source_map, &mut result)?;
28 result.insert(root_filename.into(), &krate.module);
32 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
33 if attr.name() == "path" {
40 // N.B., even when there are multiple `#[path = ...]` attributes, we just need to
41 // examine the first one, since rustc ignores the second and the subsequent ones
42 // as unused attributes.
43 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
44 attrs.iter().flat_map(path_value).next()
47 /// Recursively list all external modules included in a module.
48 fn list_submodules<'a>(
51 relative: Option<ast::Ident>,
52 source_map: &source_map::SourceMap,
53 result: &mut BTreeMap<FileName, &'a ast::Mod>,
54 ) -> Result<(), io::Error> {
55 debug!("list_submodules: search_dir: {:?}", search_dir);
56 for item in &module.items {
57 if let ast::ItemKind::Mod(ref sub_mod) = item.node {
58 if !contains_skip(&item.attrs) {
59 let is_internal = source_map.span_to_filename(item.span)
60 == source_map.span_to_filename(sub_mod.inner);
61 let (dir_path, relative) = if is_internal {
62 if let Some(path) = find_path_value(&item.attrs) {
63 (search_dir.join(&path.as_str()), None)
65 (search_dir.join(&item.ident.to_string()), None)
68 let (mod_path, relative) =
69 module_file(item.ident, &item.attrs, search_dir, relative, source_map)?;
70 let dir_path = mod_path.parent().unwrap().to_owned();
71 result.insert(FileName::Real(mod_path), sub_mod);
74 list_submodules(sub_mod, &dir_path, relative, source_map, result)?;
81 /// Finds the file corresponding to an external mod
84 attrs: &[ast::Attribute],
86 relative: Option<ast::Ident>,
87 source_map: &source_map::SourceMap,
88 ) -> Result<(PathBuf, Option<ast::Ident>), io::Error> {
89 if let Some(path) = parser::Parser::submod_path_from_attr(attrs, dir_path) {
90 return Ok((path, None));
93 match parser::Parser::default_submod_path(id, relative, dir_path, source_map).result {
94 Ok(parser::ModulePathSuccess {
99 let relative = if let DirectoryOwnership::Owned { relative } = directory_ownership {
106 Err(_) => Err(io::Error::new(
107 io::ErrorKind::Other,
108 format!("Couldn't find module {}", id),