]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/module.rs
0c8fad03d869053b0def50ac6c40153a48d52bbc
[rust.git] / src / librustc_parse / parser / module.rs
1 use super::diagnostics::Error;
2 use super::item::ItemInfo;
3 use super::Parser;
4
5 use crate::{new_sub_parser_from_file, DirectoryOwnership};
6
7 use rustc_errors::PResult;
8 use rustc_span::source_map::{FileName, SourceMap, Span, DUMMY_SP};
9 use rustc_span::symbol::sym;
10 use syntax::ast::{self, Attribute, Crate, Ident, ItemKind, Mod};
11 use syntax::attr;
12 use syntax::token::{self, TokenKind};
13
14 use std::path::{self, Path, PathBuf};
15
16 /// Information about the path to a module.
17 // Public for rustfmt usage.
18 pub struct ModulePath {
19     name: String,
20     path_exists: bool,
21     pub result: Result<ModulePathSuccess, Error>,
22 }
23
24 // Public for rustfmt usage.
25 pub struct ModulePathSuccess {
26     pub path: PathBuf,
27     pub directory_ownership: DirectoryOwnership,
28 }
29
30 impl<'a> Parser<'a> {
31     /// Parses a source module as a crate. This is the main entry point for the parser.
32     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
33         let lo = self.token.span;
34         let krate = Ok(ast::Crate {
35             attrs: self.parse_inner_attributes()?,
36             module: self.parse_mod_items(&token::Eof, lo)?,
37             span: lo.to(self.token.span),
38         });
39         krate
40     }
41
42     /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
43     pub(super) fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
44         let (in_cfg, outer_attrs) =
45             crate::config::process_configure_mod(self.sess, self.cfg_mods, outer_attrs);
46
47         let id_span = self.token.span;
48         let id = self.parse_ident()?;
49         if self.eat(&token::Semi) {
50             if in_cfg && self.recurse_into_file_modules {
51                 // This mod is in an external file. Let's go get it!
52                 let ModulePathSuccess { path, directory_ownership } =
53                     self.submod_path(id, &outer_attrs, id_span)?;
54                 let (module, attrs) =
55                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
56                 Ok((id, ItemKind::Mod(module), Some(attrs)))
57             } else {
58                 let placeholder = ast::Mod { inner: DUMMY_SP, items: Vec::new(), inline: false };
59                 Ok((id, ItemKind::Mod(placeholder), None))
60             }
61         } else {
62             let old_directory = self.directory.clone();
63             self.push_directory(id, &outer_attrs);
64
65             self.expect(&token::OpenDelim(token::Brace))?;
66             let mod_inner_lo = self.token.span;
67             let attrs = self.parse_inner_attributes()?;
68             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
69
70             self.directory = old_directory;
71             Ok((id, ItemKind::Mod(module), Some(attrs)))
72         }
73     }
74
75     /// Given a termination token, parses all of the items in a module.
76     fn parse_mod_items(&mut self, term: &TokenKind, inner_lo: Span) -> PResult<'a, Mod> {
77         let mut items = vec![];
78         while let Some(item) = self.parse_item()? {
79             items.push(item);
80             self.maybe_consume_incorrect_semicolon(&items);
81         }
82
83         if !self.eat(term) {
84             let token_str = super::token_descr(&self.token);
85             if !self.maybe_consume_incorrect_semicolon(&items) {
86                 let msg = &format!("expected item, found {}", token_str);
87                 let mut err = self.struct_span_err(self.token.span, msg);
88                 err.span_label(self.token.span, "expected item");
89                 return Err(err);
90             }
91         }
92
93         let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_span };
94
95         Ok(Mod { inner: inner_lo.to(hi), items, inline: true })
96     }
97
98     fn submod_path(
99         &mut self,
100         id: ast::Ident,
101         outer_attrs: &[Attribute],
102         id_sp: Span,
103     ) -> PResult<'a, ModulePathSuccess> {
104         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
105             return Ok(ModulePathSuccess {
106                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
107                     // All `#[path]` files are treated as though they are a `mod.rs` file.
108                     // This means that `mod foo;` declarations inside `#[path]`-included
109                     // files are siblings,
110                     //
111                     // Note that this will produce weirdness when a file named `foo.rs` is
112                     // `#[path]` included and contains a `mod foo;` declaration.
113                     // If you encounter this, it's your own darn fault :P
114                     Some(_) => DirectoryOwnership::Owned { relative: None },
115                     _ => DirectoryOwnership::UnownedViaMod,
116                 },
117                 path,
118             });
119         }
120
121         let relative = match self.directory.ownership {
122             DirectoryOwnership::Owned { relative } => relative,
123             DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
124         };
125         let paths =
126             Parser::default_submod_path(id, relative, &self.directory.path, self.sess.source_map());
127
128         match self.directory.ownership {
129             DirectoryOwnership::Owned { .. } => {
130                 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
131             }
132             DirectoryOwnership::UnownedViaBlock => {
133                 let msg = "Cannot declare a non-inline module inside a block \
134                     unless it has a path attribute";
135                 let mut err = self.struct_span_err(id_sp, msg);
136                 if paths.path_exists {
137                     let msg = format!(
138                         "Maybe `use` the module `{}` instead of redeclaring it",
139                         paths.name
140                     );
141                     err.span_note(id_sp, &msg);
142                 }
143                 Err(err)
144             }
145             DirectoryOwnership::UnownedViaMod => {
146                 let mut err =
147                     self.struct_span_err(id_sp, "cannot declare a new module at this location");
148                 if !id_sp.is_dummy() {
149                     let src_path = self.sess.source_map().span_to_filename(id_sp);
150                     if let FileName::Real(src_path) = src_path {
151                         if let Some(stem) = src_path.file_stem() {
152                             let mut dest_path = src_path.clone();
153                             dest_path.set_file_name(stem);
154                             dest_path.push("mod.rs");
155                             err.span_note(
156                                 id_sp,
157                                 &format!(
158                                     "maybe move this module `{}` to its own \
159                                                 directory via `{}`",
160                                     src_path.display(),
161                                     dest_path.display()
162                                 ),
163                             );
164                         }
165                     }
166                 }
167                 if paths.path_exists {
168                     err.span_note(
169                         id_sp,
170                         &format!(
171                             "... or maybe `use` the module `{}` instead \
172                                             of possibly redeclaring it",
173                             paths.name
174                         ),
175                     );
176                 }
177                 Err(err)
178             }
179         }
180     }
181
182     // Public for rustfmt usage.
183     pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
184         if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
185             let s = s.as_str();
186
187             // On windows, the base path might have the form
188             // `\\?\foo\bar` in which case it does not tolerate
189             // mixed `/` and `\` separators, so canonicalize
190             // `/` to `\`.
191             #[cfg(windows)]
192             let s = s.replace("/", "\\");
193             Some(dir_path.join(&*s))
194         } else {
195             None
196         }
197     }
198
199     /// Returns a path to a module.
200     // Public for rustfmt usage.
201     pub fn default_submod_path(
202         id: ast::Ident,
203         relative: Option<ast::Ident>,
204         dir_path: &Path,
205         source_map: &SourceMap,
206     ) -> ModulePath {
207         // If we're in a foo.rs file instead of a mod.rs file,
208         // we need to look for submodules in
209         // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
210         // `./<id>.rs` and `./<id>/mod.rs`.
211         let relative_prefix_string;
212         let relative_prefix = if let Some(ident) = relative {
213             relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
214             &relative_prefix_string
215         } else {
216             ""
217         };
218
219         let mod_name = id.name.to_string();
220         let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
221         let secondary_path_str =
222             format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
223         let default_path = dir_path.join(&default_path_str);
224         let secondary_path = dir_path.join(&secondary_path_str);
225         let default_exists = source_map.file_exists(&default_path);
226         let secondary_exists = source_map.file_exists(&secondary_path);
227
228         let result = match (default_exists, secondary_exists) {
229             (true, false) => Ok(ModulePathSuccess {
230                 path: default_path,
231                 directory_ownership: DirectoryOwnership::Owned { relative: Some(id) },
232             }),
233             (false, true) => Ok(ModulePathSuccess {
234                 path: secondary_path,
235                 directory_ownership: DirectoryOwnership::Owned { relative: None },
236             }),
237             (false, false) => Err(Error::FileNotFoundForModule {
238                 mod_name: mod_name.clone(),
239                 default_path: default_path_str,
240                 secondary_path: secondary_path_str,
241                 dir_path: dir_path.display().to_string(),
242             }),
243             (true, true) => Err(Error::DuplicatePaths {
244                 mod_name: mod_name.clone(),
245                 default_path: default_path_str,
246                 secondary_path: secondary_path_str,
247             }),
248         };
249
250         ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
251     }
252
253     /// Reads a module from a source file.
254     fn eval_src_mod(
255         &mut self,
256         path: PathBuf,
257         directory_ownership: DirectoryOwnership,
258         name: String,
259         id_sp: Span,
260     ) -> PResult<'a, (Mod, Vec<Attribute>)> {
261         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
262         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
263             let mut err = String::from("circular modules: ");
264             let len = included_mod_stack.len();
265             for p in &included_mod_stack[i..len] {
266                 err.push_str(&p.to_string_lossy());
267                 err.push_str(" -> ");
268             }
269             err.push_str(&path.to_string_lossy());
270             return Err(self.struct_span_err(id_sp, &err[..]));
271         }
272         included_mod_stack.push(path.clone());
273         drop(included_mod_stack);
274
275         let mut p0 =
276             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
277         p0.cfg_mods = self.cfg_mods;
278         let mod_inner_lo = p0.token.span;
279         let mod_attrs = p0.parse_inner_attributes()?;
280         let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
281         m0.inline = false;
282         self.sess.included_mod_stack.borrow_mut().pop();
283         Ok((m0, mod_attrs))
284     }
285
286     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
287         if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
288             self.directory.path.push(&*path.as_str());
289             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
290         } else {
291             // We have to push on the current module name in the case of relative
292             // paths in order to ensure that any additional module paths from inline
293             // `mod x { ... }` come after the relative extension.
294             //
295             // For example, a `mod z { ... }` inside `x/y.rs` should set the current
296             // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
297             if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
298                 if let Some(ident) = relative.take() {
299                     // remove the relative offset
300                     self.directory.path.push(&*ident.as_str());
301                 }
302             }
303             self.directory.path.push(&*id.as_str());
304         }
305     }
306 }