]> git.lizzy.rs Git - rust.git/blob - src/modules.rs
Merge pull request #3129 from otavio/issue-3104
[rust.git] / src / modules.rs
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.
4 //
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.
10
11 use std::collections::BTreeMap;
12 use std::io;
13 use std::path::{Path, PathBuf};
14
15 use syntax::ast;
16 use syntax::parse::{parser, DirectoryOwnership};
17 use syntax::source_map;
18 use syntax_pos::symbol::Symbol;
19
20 use config::FileName;
21 use utils::contains_skip;
22
23 /// List all the files containing modules of a crate.
24 /// If a file is used twice in a crate, it appears only once.
25 pub fn list_files<'a>(
26     krate: &'a ast::Crate,
27     source_map: &source_map::SourceMap,
28 ) -> Result<BTreeMap<FileName, &'a ast::Mod>, io::Error> {
29     let mut result = BTreeMap::new(); // Enforce file order determinism
30     let root_filename = source_map.span_to_filename(krate.span);
31     {
32         let parent = match root_filename {
33             source_map::FileName::Real(ref path) => path.parent().unwrap(),
34             _ => Path::new(""),
35         };
36         list_submodules(&krate.module, parent, None, source_map, &mut result)?;
37     }
38     result.insert(root_filename.into(), &krate.module);
39     Ok(result)
40 }
41
42 fn path_value(attr: &ast::Attribute) -> Option<Symbol> {
43     if attr.name() == "path" {
44         attr.value_str()
45     } else {
46         None
47     }
48 }
49
50 // N.B. Even when there are multiple `#[path = ...]` attributes, we just need to
51 // examine the first one, since rustc ignores the second and the subsequent ones
52 // as unused attributes.
53 fn find_path_value(attrs: &[ast::Attribute]) -> Option<Symbol> {
54     attrs.iter().flat_map(path_value).next()
55 }
56
57 /// Recursively list all external modules included in a module.
58 fn list_submodules<'a>(
59     module: &'a ast::Mod,
60     search_dir: &Path,
61     relative: Option<ast::Ident>,
62     source_map: &source_map::SourceMap,
63     result: &mut BTreeMap<FileName, &'a ast::Mod>,
64 ) -> Result<(), io::Error> {
65     debug!("list_submodules: search_dir: {:?}", search_dir);
66     for item in &module.items {
67         if let ast::ItemKind::Mod(ref sub_mod) = item.node {
68             if !contains_skip(&item.attrs) {
69                 let is_internal = source_map.span_to_filename(item.span)
70                     == source_map.span_to_filename(sub_mod.inner);
71                 let (dir_path, relative) = if is_internal {
72                     if let Some(path) = find_path_value(&item.attrs) {
73                         (search_dir.join(&path.as_str()), None)
74                     } else {
75                         (search_dir.join(&item.ident.to_string()), None)
76                     }
77                 } else {
78                     let (mod_path, relative) =
79                         module_file(item.ident, &item.attrs, search_dir, relative, source_map)?;
80                     let dir_path = mod_path.parent().unwrap().to_owned();
81                     result.insert(FileName::Real(mod_path), sub_mod);
82                     (dir_path, relative)
83                 };
84                 list_submodules(sub_mod, &dir_path, relative, source_map, result)?;
85             }
86         }
87     }
88     Ok(())
89 }
90
91 /// Find the file corresponding to an external mod
92 fn module_file(
93     id: ast::Ident,
94     attrs: &[ast::Attribute],
95     dir_path: &Path,
96     relative: Option<ast::Ident>,
97     source_map: &source_map::SourceMap,
98 ) -> Result<(PathBuf, Option<ast::Ident>), io::Error> {
99     if let Some(path) = parser::Parser::submod_path_from_attr(attrs, dir_path) {
100         return Ok((path, None));
101     }
102
103     match parser::Parser::default_submod_path(id, relative, dir_path, source_map).result {
104         Ok(parser::ModulePathSuccess {
105             path,
106             directory_ownership,
107             ..
108         }) => {
109             let relative = if let DirectoryOwnership::Owned { relative } = directory_ownership {
110                 relative
111             } else {
112                 None
113             };
114             Ok((path, relative))
115         }
116         Err(_) => Err(io::Error::new(
117             io::ErrorKind::Other,
118             format!("Couldn't find module {}", id),
119         )),
120     }
121 }