1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::collections::BTreeMap;
13 use std::path::{Path, PathBuf};
17 use syntax::parse::{parser, DirectoryOwnership};
20 use utils::contains_skip;
22 /// List all the files containing modules of a crate.
23 /// If a file is used twice in a crate, it appears only once.
24 pub fn list_files<'a>(
25 krate: &'a ast::Crate,
26 codemap: &codemap::CodeMap,
27 ) -> Result<BTreeMap<FileName, &'a ast::Mod>, io::Error> {
28 let mut result = BTreeMap::new(); // Enforce file order determinism
29 let root_filename = codemap.span_to_filename(krate.span);
31 let parent = match root_filename {
32 codemap::FileName::Real(ref path) => path.parent().unwrap(),
35 list_submodules(&krate.module, parent, None, codemap, &mut result)?;
37 result.insert(root_filename.into(), &krate.module);
41 /// Recursively list all external modules included in a module.
42 fn list_submodules<'a>(
45 relative: Option<ast::Ident>,
46 codemap: &codemap::CodeMap,
47 result: &mut BTreeMap<FileName, &'a ast::Mod>,
48 ) -> Result<(), io::Error> {
49 debug!("list_submodules: search_dir: {:?}", search_dir);
50 for item in &module.items {
51 if let ast::ItemKind::Mod(ref sub_mod) = item.node {
52 if !contains_skip(&item.attrs) {
54 codemap.span_to_filename(item.span) == codemap.span_to_filename(sub_mod.inner);
55 let (dir_path, relative) = if is_internal {
56 (search_dir.join(&item.ident.to_string()), None)
58 let (mod_path, relative) =
59 module_file(item.ident, &item.attrs, search_dir, relative, codemap)?;
60 let dir_path = mod_path.parent().unwrap().to_owned();
61 result.insert(FileName::Real(mod_path), sub_mod);
64 list_submodules(sub_mod, &dir_path, relative, codemap, result)?;
71 /// Find the file corresponding to an external mod
74 attrs: &[ast::Attribute],
76 relative: Option<ast::Ident>,
77 codemap: &codemap::CodeMap,
78 ) -> Result<(PathBuf, Option<ast::Ident>), io::Error> {
79 if let Some(path) = parser::Parser::submod_path_from_attr(attrs, dir_path) {
80 return Ok((path, None));
83 match parser::Parser::default_submod_path(id, relative, dir_path, codemap).result {
84 Ok(parser::ModulePathSuccess {
89 let relative = if let DirectoryOwnership::Owned { relative } = directory_ownership {
96 Err(_) => Err(io::Error::new(
98 format!("Couldn't find module {}", id),