1 use rustc_ast::ast::{self, Attribute, Ident, Mod};
2 use rustc_ast::{attr, token};
3 use rustc_errors::{struct_span_err, PResult};
4 use rustc_parse::new_sub_parser_from_file;
5 use rustc_session::parse::ParseSess;
6 use rustc_span::source_map::{FileName, Span};
7 use rustc_span::symbol::sym;
9 use std::path::{self, Path, PathBuf};
12 pub struct Directory {
14 pub ownership: DirectoryOwnership,
17 #[derive(Copy, Clone)]
18 pub enum DirectoryOwnership {
20 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
21 relative: Option<ast::Ident>,
27 /// Information about the path to a module.
28 // Public for rustfmt usage.
29 pub struct ModulePath<'a> {
32 pub result: PResult<'a, ModulePathSuccess>,
35 // Public for rustfmt usage.
36 pub struct ModulePathSuccess {
38 pub ownership: DirectoryOwnership,
41 crate fn parse_external_mod(
44 span: Span, // The span to blame on errors.
45 Directory { mut ownership, path }: Directory,
46 attrs: &mut Vec<Attribute>,
47 pop_mod_stack: &mut bool,
48 ) -> (Mod, Directory) {
49 // We bail on the first error, but that error does not cause a fatal error... (1)
50 let result: PResult<'_, _> = try {
51 // Extract the file path and the new ownership.
52 let mp = submod_path(sess, id, span, &attrs, ownership, &path)?;
53 ownership = mp.ownership;
55 // Ensure file paths are acyclic.
56 let mut included_mod_stack = sess.included_mod_stack.borrow_mut();
57 error_on_circular_module(sess, span, &mp.path, &included_mod_stack)?;
58 included_mod_stack.push(mp.path.clone());
59 *pop_mod_stack = true; // We have pushed, so notify caller.
60 drop(included_mod_stack);
62 // Actually parse the external file as amodule.
63 let mut p0 = new_sub_parser_from_file(sess, &mp.path, Some(id.to_string()), span);
64 let mut module = p0.parse_mod(&token::Eof)?;
65 module.0.inline = false;
68 // (1) ...instead, we return a dummy module.
69 let (module, mut new_attrs) = result.map_err(|mut err| err.emit()).unwrap_or_default();
70 attrs.append(&mut new_attrs);
72 // Extract the directory path for submodules of `module`.
73 let path = sess.source_map().span_to_unmapped_path(module.inner);
74 let mut path = match path {
75 FileName::Real(path) => path,
76 other => PathBuf::from(other.to_string()),
80 (module, Directory { ownership, path })
83 fn error_on_circular_module<'a>(
87 included_mod_stack: &[PathBuf],
88 ) -> PResult<'a, ()> {
89 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
90 let mut err = String::from("circular modules: ");
91 for p in &included_mod_stack[i..] {
92 err.push_str(&p.to_string_lossy());
95 err.push_str(&path.to_string_lossy());
96 return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
101 crate fn push_directory(
104 Directory { mut ownership, mut path }: Directory,
106 if let Some(filename) = attr::first_attr_value_str_by_name(attrs, sym::path) {
107 path.push(&*filename.as_str());
108 ownership = DirectoryOwnership::Owned { relative: None };
110 // We have to push on the current module name in the case of relative
111 // paths in order to ensure that any additional module paths from inline
112 // `mod x { ... }` come after the relative extension.
114 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
115 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
116 if let DirectoryOwnership::Owned { relative } = &mut ownership {
117 if let Some(ident) = relative.take() {
118 // Remove the relative offset.
119 path.push(&*ident.as_str());
122 path.push(&*id.as_str());
124 Directory { ownership, path }
132 ownership: DirectoryOwnership,
134 ) -> PResult<'a, ModulePathSuccess> {
135 if let Some(path) = submod_path_from_attr(attrs, dir_path) {
136 let ownership = match path.file_name().and_then(|s| s.to_str()) {
137 // All `#[path]` files are treated as though they are a `mod.rs` file.
138 // This means that `mod foo;` declarations inside `#[path]`-included
139 // files are siblings,
141 // Note that this will produce weirdness when a file named `foo.rs` is
142 // `#[path]` included and contains a `mod foo;` declaration.
143 // If you encounter this, it's your own darn fault :P
144 Some(_) => DirectoryOwnership::Owned { relative: None },
145 _ => DirectoryOwnership::UnownedViaMod,
147 return Ok(ModulePathSuccess { ownership, path });
150 let relative = match ownership {
151 DirectoryOwnership::Owned { relative } => relative,
152 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
154 let ModulePath { path_exists, name, result } =
155 default_submod_path(sess, id, span, relative, dir_path);
157 DirectoryOwnership::Owned { .. } => Ok(result?),
158 DirectoryOwnership::UnownedViaBlock => {
159 let _ = result.map_err(|mut err| err.cancel());
160 error_decl_mod_in_block(sess, span, path_exists, &name)
162 DirectoryOwnership::UnownedViaMod => {
163 let _ = result.map_err(|mut err| err.cancel());
164 error_cannot_declare_mod_here(sess, span, path_exists, &name)
169 fn error_decl_mod_in_block<'a, T>(
174 ) -> PResult<'a, T> {
175 let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
176 let mut err = sess.span_diagnostic.struct_span_err(span, msg);
178 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
179 err.span_note(span, &msg);
184 fn error_cannot_declare_mod_here<'a, T>(
189 ) -> PResult<'a, T> {
191 sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
192 if !span.is_dummy() {
193 if let FileName::Real(src_path) = sess.source_map().span_to_filename(span) {
194 if let Some(stem) = src_path.file_stem() {
195 let mut dest_path = src_path.clone();
196 dest_path.set_file_name(stem);
197 dest_path.push("mod.rs");
201 "maybe move this module `{}` to its own directory via `{}`",
212 &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
218 /// Derive a submodule path from the first found `#[path = "path_string"]`.
219 /// The provided `dir_path` is joined with the `path_string`.
220 // Public for rustfmt usage.
221 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
222 // Extract path string from first `#[path = "path_string"]` attribute.
223 let path_string = attr::first_attr_value_str_by_name(attrs, sym::path)?;
224 let path_string = path_string.as_str();
226 // On windows, the base path might have the form
227 // `\\?\foo\bar` in which case it does not tolerate
228 // mixed `/` and `\` separators, so canonicalize
231 let path_string = path_string.replace("/", "\\");
233 Some(dir_path.join(&*path_string))
236 /// Returns a path to a module.
237 // Public for rustfmt usage.
238 pub fn default_submod_path<'a>(
242 relative: Option<ast::Ident>,
244 ) -> ModulePath<'a> {
245 // If we're in a foo.rs file instead of a mod.rs file,
246 // we need to look for submodules in
247 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
248 // `./<id>.rs` and `./<id>/mod.rs`.
249 let relative_prefix_string;
250 let relative_prefix = if let Some(ident) = relative {
251 relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
252 &relative_prefix_string
257 let mod_name = id.name.to_string();
258 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
259 let secondary_path_str =
260 format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
261 let default_path = dir_path.join(&default_path_str);
262 let secondary_path = dir_path.join(&secondary_path_str);
263 let default_exists = sess.source_map().file_exists(&default_path);
264 let secondary_exists = sess.source_map().file_exists(&secondary_path);
266 let result = match (default_exists, secondary_exists) {
267 (true, false) => Ok(ModulePathSuccess {
269 ownership: DirectoryOwnership::Owned { relative: Some(id) },
271 (false, true) => Ok(ModulePathSuccess {
272 path: secondary_path,
273 ownership: DirectoryOwnership::Owned { relative: None },
276 let mut err = struct_span_err!(
277 sess.span_diagnostic,
280 "file not found for module `{}`",
284 "to create the module `{}`, create file \"{}\"",
286 default_path.display(),
291 let mut err = struct_span_err!(
292 sess.span_diagnostic,
295 "file for module `{}` found at both {} and {}",
300 err.help("delete or rename one of them to remove the ambiguity");
305 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }