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