1 use super::diagnostics::Error;
2 use super::item::ItemInfo;
5 use crate::{new_sub_parser_from_file, DirectoryOwnership};
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};
12 use syntax::token::{self, TokenKind};
14 use std::path::{self, Path, PathBuf};
16 /// Information about the path to a module.
17 // Public for rustfmt usage.
18 pub struct ModulePath {
21 pub result: Result<ModulePathSuccess, Error>,
24 // Public for rustfmt usage.
25 pub struct ModulePathSuccess {
27 pub directory_ownership: DirectoryOwnership,
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),
42 /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
43 pub(super) fn parse_item_mod(&mut self, attrs: &mut Vec<Attribute>) -> PResult<'a, ItemInfo> {
44 let in_cfg = crate::config::process_configure_mod(self.sess, self.cfg_mods, attrs);
46 let id_span = self.token.span;
47 let id = self.parse_ident()?;
48 let (module, mut inner_attrs) = if self.eat(&token::Semi) {
49 if in_cfg && self.recurse_into_file_modules {
50 // This mod is in an external file. Let's go get it!
51 let ModulePathSuccess { path, directory_ownership } =
52 self.submod_path(id, &attrs, id_span)?;
53 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?
55 (ast::Mod { inner: DUMMY_SP, items: Vec::new(), inline: false }, Vec::new())
58 let old_directory = self.directory.clone();
59 self.push_directory(id, &attrs);
61 self.expect(&token::OpenDelim(token::Brace))?;
62 let mod_inner_lo = self.token.span;
63 let inner_attrs = self.parse_inner_attributes()?;
64 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
66 self.directory = old_directory;
69 attrs.append(&mut inner_attrs);
70 Ok((id, ItemKind::Mod(module)))
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()? {
78 self.maybe_consume_incorrect_semicolon(&items);
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");
91 let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_span };
93 Ok(Mod { inner: inner_lo.to(hi), items, inline: true })
99 outer_attrs: &[Attribute],
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,
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,
119 let relative = match self.directory.ownership {
120 DirectoryOwnership::Owned { relative } => relative,
121 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
124 Parser::default_submod_path(id, relative, &self.directory.path, self.sess.source_map());
126 match self.directory.ownership {
127 DirectoryOwnership::Owned { .. } => {
128 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
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 {
136 "Maybe `use` the module `{}` instead of redeclaring it",
139 err.span_note(id_sp, &msg);
143 DirectoryOwnership::UnownedViaMod => {
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");
156 "maybe move this module `{}` to its own \
165 if paths.path_exists {
169 "... or maybe `use` the module `{}` instead \
170 of possibly redeclaring it",
180 // Public for rustfmt usage.
181 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
182 if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
185 // On windows, the base path might have the form
186 // `\\?\foo\bar` in which case it does not tolerate
187 // mixed `/` and `\` separators, so canonicalize
190 let s = s.replace("/", "\\");
191 Some(dir_path.join(&*s))
197 /// Returns a path to a module.
198 // Public for rustfmt usage.
199 pub fn default_submod_path(
201 relative: Option<ast::Ident>,
203 source_map: &SourceMap,
205 // If we're in a foo.rs file instead of a mod.rs file,
206 // we need to look for submodules in
207 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
208 // `./<id>.rs` and `./<id>/mod.rs`.
209 let relative_prefix_string;
210 let relative_prefix = if let Some(ident) = relative {
211 relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
212 &relative_prefix_string
217 let mod_name = id.name.to_string();
218 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
219 let secondary_path_str =
220 format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
221 let default_path = dir_path.join(&default_path_str);
222 let secondary_path = dir_path.join(&secondary_path_str);
223 let default_exists = source_map.file_exists(&default_path);
224 let secondary_exists = source_map.file_exists(&secondary_path);
226 let result = match (default_exists, secondary_exists) {
227 (true, false) => Ok(ModulePathSuccess {
229 directory_ownership: DirectoryOwnership::Owned { relative: Some(id) },
231 (false, true) => Ok(ModulePathSuccess {
232 path: secondary_path,
233 directory_ownership: DirectoryOwnership::Owned { relative: None },
235 (false, false) => Err(Error::FileNotFoundForModule {
236 mod_name: mod_name.clone(),
237 default_path: default_path_str,
238 secondary_path: secondary_path_str,
239 dir_path: dir_path.display().to_string(),
241 (true, true) => Err(Error::DuplicatePaths {
242 mod_name: mod_name.clone(),
243 default_path: default_path_str,
244 secondary_path: secondary_path_str,
248 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
251 /// Reads a module from a source file.
255 directory_ownership: DirectoryOwnership,
258 ) -> PResult<'a, (Mod, Vec<Attribute>)> {
259 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
260 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
261 let mut err = String::from("circular modules: ");
262 let len = included_mod_stack.len();
263 for p in &included_mod_stack[i..len] {
264 err.push_str(&p.to_string_lossy());
265 err.push_str(" -> ");
267 err.push_str(&path.to_string_lossy());
268 return Err(self.struct_span_err(id_sp, &err[..]));
270 included_mod_stack.push(path.clone());
271 drop(included_mod_stack);
274 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
275 p0.cfg_mods = self.cfg_mods;
276 let mod_inner_lo = p0.token.span;
277 let mod_attrs = p0.parse_inner_attributes()?;
278 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
280 self.sess.included_mod_stack.borrow_mut().pop();
284 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
285 if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
286 self.directory.path.push(&*path.as_str());
287 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
289 // We have to push on the current module name in the case of relative
290 // paths in order to ensure that any additional module paths from inline
291 // `mod x { ... }` come after the relative extension.
293 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
294 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
295 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
296 if let Some(ident) = relative.take() {
297 // remove the relative offset
298 self.directory.path.push(&*ident.as_str());
301 self.directory.path.push(&*id.as_str());