2 use rustc_ast::{token, Attribute, Item};
3 use rustc_errors::{struct_span_err, PResult};
4 use rustc_parse::new_parser_from_file;
5 use rustc_session::parse::ParseSess;
6 use rustc_session::Session;
7 use rustc_span::source_map::{FileName, Span};
8 use rustc_span::symbol::{sym, Ident};
10 use std::path::{self, Path, PathBuf};
13 pub struct Directory {
15 pub ownership: DirectoryOwnership,
18 #[derive(Copy, Clone)]
19 pub enum DirectoryOwnership {
21 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
22 relative: Option<Ident>,
28 /// Information about the path to a module.
29 // Public for rustfmt usage.
30 pub struct ModulePath<'a> {
33 pub result: PResult<'a, ModulePathSuccess>,
36 // Public for rustfmt usage.
37 pub struct ModulePathSuccess {
39 pub ownership: DirectoryOwnership,
42 crate fn parse_external_mod(
45 span: Span, // The span to blame on errors.
46 Directory { mut ownership, path }: Directory,
47 attrs: &mut Vec<Attribute>,
48 pop_mod_stack: &mut bool,
49 ) -> (Vec<P<Item>>, Span, Directory) {
50 // We bail on the first error, but that error does not cause a fatal error... (1)
51 let result: PResult<'_, _> = try {
52 // Extract the file path and the new ownership.
53 let mp = submod_path(sess, id, span, &attrs, ownership, &path)?;
54 ownership = mp.ownership;
56 // Ensure file paths are acyclic.
57 let mut included_mod_stack = sess.parse_sess.included_mod_stack.borrow_mut();
58 error_on_circular_module(&sess.parse_sess, span, &mp.path, &included_mod_stack)?;
59 included_mod_stack.push(mp.path.clone());
60 *pop_mod_stack = true; // We have pushed, so notify caller.
61 drop(included_mod_stack);
63 // Actually parse the external file as a module.
64 let mut parser = new_parser_from_file(&sess.parse_sess, &mp.path, Some(span));
65 let (mut inner_attrs, items, inner_span) = parser.parse_mod(&token::Eof)?;
66 attrs.append(&mut inner_attrs);
69 // (1) ...instead, we return a dummy module.
70 let (items, inner_span) = result.map_err(|mut err| err.emit()).unwrap_or_default();
72 // Extract the directory path for submodules of the module.
73 let path = sess.source_map().span_to_unmapped_path(inner_span);
74 let mut path = match path {
75 FileName::Real(name) => name.into_local_path(),
76 other => PathBuf::from(other.to_string()),
80 (items, inner_span, 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(
105 Directory { mut ownership, mut path }: Directory,
107 if let Some(filename) = sess.first_attr_value_str_by_name(attrs, sym::path) {
108 path.push(&*filename.as_str());
109 ownership = DirectoryOwnership::Owned { relative: None };
111 // We have to push on the current module name in the case of relative
112 // paths in order to ensure that any additional module paths from inline
113 // `mod x { ... }` come after the relative extension.
115 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
116 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
117 if let DirectoryOwnership::Owned { relative } = &mut ownership {
118 if let Some(ident) = relative.take() {
119 // Remove the relative offset.
120 path.push(&*ident.as_str());
123 path.push(&*id.as_str());
125 Directory { ownership, path }
133 ownership: DirectoryOwnership,
135 ) -> PResult<'a, ModulePathSuccess> {
136 if let Some(path) = submod_path_from_attr(sess, attrs, dir_path) {
137 let ownership = match path.file_name().and_then(|s| s.to_str()) {
138 // All `#[path]` files are treated as though they are a `mod.rs` file.
139 // This means that `mod foo;` declarations inside `#[path]`-included
140 // files are siblings,
142 // Note that this will produce weirdness when a file named `foo.rs` is
143 // `#[path]` included and contains a `mod foo;` declaration.
144 // If you encounter this, it's your own darn fault :P
145 Some(_) => DirectoryOwnership::Owned { relative: None },
146 _ => DirectoryOwnership::UnownedViaMod,
148 return Ok(ModulePathSuccess { ownership, path });
151 let relative = match ownership {
152 DirectoryOwnership::Owned { relative } => relative,
153 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
155 let ModulePath { path_exists, name, result } =
156 default_submod_path(&sess.parse_sess, id, span, relative, dir_path);
158 DirectoryOwnership::Owned { .. } => Ok(result?),
159 DirectoryOwnership::UnownedViaBlock => {
160 let _ = result.map_err(|mut err| err.cancel());
161 error_decl_mod_in_block(&sess.parse_sess, span, path_exists, &name)
163 DirectoryOwnership::UnownedViaMod => {
164 let _ = result.map_err(|mut err| err.cancel());
165 error_cannot_declare_mod_here(&sess.parse_sess, span, path_exists, &name)
170 fn error_decl_mod_in_block<'a, T>(
175 ) -> PResult<'a, T> {
176 let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
177 let mut err = sess.span_diagnostic.struct_span_err(span, msg);
179 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
180 err.span_note(span, &msg);
185 fn error_cannot_declare_mod_here<'a, T>(
190 ) -> PResult<'a, T> {
192 sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
193 if !span.is_dummy() {
194 if let FileName::Real(src_name) = sess.source_map().span_to_filename(span) {
195 let src_path = src_name.into_local_path();
196 if let Some(stem) = src_path.file_stem() {
197 let mut dest_path = src_path.clone();
198 dest_path.set_file_name(stem);
199 dest_path.push("mod.rs");
203 "maybe move this module `{}` to its own directory via `{}`",
214 &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
220 /// Derive a submodule path from the first found `#[path = "path_string"]`.
221 /// The provided `dir_path` is joined with the `path_string`.
222 pub(super) fn submod_path_from_attr(
226 ) -> Option<PathBuf> {
227 // Extract path string from first `#[path = "path_string"]` attribute.
228 let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?;
229 let path_string = path_string.as_str();
231 // On windows, the base path might have the form
232 // `\\?\foo\bar` in which case it does not tolerate
233 // mixed `/` and `\` separators, so canonicalize
236 let path_string = path_string.replace("/", "\\");
238 Some(dir_path.join(&*path_string))
241 /// Returns a path to a module.
242 // Public for rustfmt usage.
243 pub fn default_submod_path<'a>(
247 relative: Option<Ident>,
249 ) -> ModulePath<'a> {
250 // If we're in a foo.rs file instead of a mod.rs file,
251 // we need to look for submodules in
252 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
253 // `./<id>.rs` and `./<id>/mod.rs`.
254 let relative_prefix_string;
255 let relative_prefix = if let Some(ident) = relative {
256 relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
257 &relative_prefix_string
262 let mod_name = id.name.to_string();
263 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
264 let secondary_path_str =
265 format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
266 let default_path = dir_path.join(&default_path_str);
267 let secondary_path = dir_path.join(&secondary_path_str);
268 let default_exists = sess.source_map().file_exists(&default_path);
269 let secondary_exists = sess.source_map().file_exists(&secondary_path);
271 let result = match (default_exists, secondary_exists) {
272 (true, false) => Ok(ModulePathSuccess {
274 ownership: DirectoryOwnership::Owned { relative: Some(id) },
276 (false, true) => Ok(ModulePathSuccess {
277 path: secondary_path,
278 ownership: DirectoryOwnership::Owned { relative: None },
281 let mut err = struct_span_err!(
282 sess.span_diagnostic,
285 "file not found for module `{}`",
289 "to create the module `{}`, create file \"{}\"",
291 default_path.display(),
296 let mut err = struct_span_err!(
297 sess.span_diagnostic,
300 "file for module `{}` found at both {} and {}",
305 err.help("delete or rename one of them to remove the ambiguity");
310 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }