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