2 use super::item::ItemInfo;
3 use super::diagnostics::Error;
5 use crate::{new_sub_parser_from_file, DirectoryOwnership};
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};
12 use syntax_pos::symbol::sym;
15 use std::path::{self, Path, PathBuf};
17 /// Information about the path to a module.
18 pub(super) struct ModulePath {
21 pub result: Result<ModulePathSuccess, Error>,
24 pub(super) struct ModulePathSuccess {
26 pub directory_ownership: DirectoryOwnership,
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),
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)(
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)?;
58 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
59 Ok((id, ItemKind::Mod(module), Some(attrs)))
61 let placeholder = ast::Mod {
66 Ok((id, ItemKind::Mod(placeholder), None))
69 let old_directory = self.directory.clone();
70 self.push_directory(id, &outer_attrs);
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)?;
77 self.directory = old_directory;
78 Ok((id, ItemKind::Mod(module), Some(attrs)))
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()? {
87 self.maybe_consume_incorrect_semicolon(&items);
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");
99 let hi = if self.token.span.is_dummy() {
106 inner: inner_lo.to(hi),
115 outer_attrs: &[Attribute],
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,
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,
135 let relative = match self.directory.ownership {
136 DirectoryOwnership::Owned { relative } => relative,
137 DirectoryOwnership::UnownedViaBlock |
138 DirectoryOwnership::UnownedViaMod => None,
140 let paths = Parser::default_submod_path(
141 id, relative, &self.directory.path, self.sess.source_map());
143 match self.directory.ownership {
144 DirectoryOwnership::Owned { .. } => {
145 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
147 DirectoryOwnership::UnownedViaBlock => {
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",
155 err.span_note(id_sp, &msg);
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");
170 &format!("maybe move this module `{}` to its own \
171 directory via `{}`", src_path.display(),
172 dest_path.display()));
176 if paths.path_exists {
178 &format!("... or maybe `use` the module `{}` instead \
179 of possibly redeclaring it",
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) {
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
196 let s = s.replace("/", "\\");
197 Some(dir_path.join(&*s))
203 /// Returns a path to a module.
204 pub(super) fn default_submod_path(
206 relative: Option<ast::Ident>,
208 source_map: &SourceMap) -> ModulePath
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
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);
231 let result = match (default_exists, secondary_exists) {
232 (true, false) => Ok(ModulePathSuccess {
234 directory_ownership: DirectoryOwnership::Owned {
238 (false, true) => Ok(ModulePathSuccess {
239 path: secondary_path,
240 directory_ownership: DirectoryOwnership::Owned {
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(),
250 (true, true) => Err(Error::DuplicatePaths {
251 mod_name: mod_name.clone(),
252 default_path: default_path_str,
253 secondary_path: secondary_path_str,
259 path_exists: default_exists || secondary_exists,
264 /// Reads a module from a source file.
268 directory_ownership: DirectoryOwnership,
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(" -> ");
280 err.push_str(&path.to_string_lossy());
281 return Err(self.span_fatal(id_sp, &err[..]));
283 included_mod_stack.push(path.clone());
284 drop(included_mod_stack);
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)?;
293 self.sess.included_mod_stack.borrow_mut().pop();
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 };
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.
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());
313 self.directory.path.to_mut().push(&*id.as_str());