1 use rustc_ast::ast::{Attribute, Mod};
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 ) -> (Mod, 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.
65 new_parser_from_file(&sess.parse_sess, &mp.path, Some(span)).parse_mod(&token::Eof)?;
66 module.0.inline = false;
69 // (1) ...instead, we return a dummy module.
70 let (module, mut new_attrs) = result.map_err(|mut err| err.emit()).unwrap_or_default();
71 attrs.append(&mut new_attrs);
73 // Extract the directory path for submodules of `module`.
74 let path = sess.source_map().span_to_unmapped_path(module.inner);
75 let mut path = match path {
76 FileName::Real(name) => name.into_local_path(),
77 other => PathBuf::from(other.to_string()),
81 (module, Directory { ownership, path })
84 fn error_on_circular_module<'a>(
88 included_mod_stack: &[PathBuf],
89 ) -> PResult<'a, ()> {
90 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
91 let mut err = String::from("circular modules: ");
92 for p in &included_mod_stack[i..] {
93 err.push_str(&p.to_string_lossy());
96 err.push_str(&path.to_string_lossy());
97 return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
102 crate fn push_directory(
106 Directory { mut ownership, mut path }: Directory,
108 if let Some(filename) = sess.first_attr_value_str_by_name(attrs, sym::path) {
109 path.push(&*filename.as_str());
110 ownership = DirectoryOwnership::Owned { relative: None };
112 // We have to push on the current module name in the case of relative
113 // paths in order to ensure that any additional module paths from inline
114 // `mod x { ... }` come after the relative extension.
116 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
117 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
118 if let DirectoryOwnership::Owned { relative } = &mut ownership {
119 if let Some(ident) = relative.take() {
120 // Remove the relative offset.
121 path.push(&*ident.as_str());
124 path.push(&*id.as_str());
126 Directory { ownership, path }
134 ownership: DirectoryOwnership,
136 ) -> PResult<'a, ModulePathSuccess> {
137 if let Some(path) = submod_path_from_attr(sess, attrs, dir_path) {
138 let ownership = match path.file_name().and_then(|s| s.to_str()) {
139 // All `#[path]` files are treated as though they are a `mod.rs` file.
140 // This means that `mod foo;` declarations inside `#[path]`-included
141 // files are siblings,
143 // Note that this will produce weirdness when a file named `foo.rs` is
144 // `#[path]` included and contains a `mod foo;` declaration.
145 // If you encounter this, it's your own darn fault :P
146 Some(_) => DirectoryOwnership::Owned { relative: None },
147 _ => DirectoryOwnership::UnownedViaMod,
149 return Ok(ModulePathSuccess { ownership, path });
152 let relative = match ownership {
153 DirectoryOwnership::Owned { relative } => relative,
154 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
156 let ModulePath { path_exists, name, result } =
157 default_submod_path(&sess.parse_sess, id, span, relative, dir_path);
159 DirectoryOwnership::Owned { .. } => Ok(result?),
160 DirectoryOwnership::UnownedViaBlock => {
161 let _ = result.map_err(|mut err| err.cancel());
162 error_decl_mod_in_block(&sess.parse_sess, span, path_exists, &name)
164 DirectoryOwnership::UnownedViaMod => {
165 let _ = result.map_err(|mut err| err.cancel());
166 error_cannot_declare_mod_here(&sess.parse_sess, span, path_exists, &name)
171 fn error_decl_mod_in_block<'a, T>(
176 ) -> PResult<'a, T> {
177 let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
178 let mut err = sess.span_diagnostic.struct_span_err(span, msg);
180 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
181 err.span_note(span, &msg);
186 fn error_cannot_declare_mod_here<'a, T>(
191 ) -> PResult<'a, T> {
193 sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
194 if !span.is_dummy() {
195 if let FileName::Real(src_name) = sess.source_map().span_to_filename(span) {
196 let src_path = src_name.into_local_path();
197 if let Some(stem) = src_path.file_stem() {
198 let mut dest_path = src_path.clone();
199 dest_path.set_file_name(stem);
200 dest_path.push("mod.rs");
204 "maybe move this module `{}` to its own directory via `{}`",
215 &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
221 /// Derive a submodule path from the first found `#[path = "path_string"]`.
222 /// The provided `dir_path` is joined with the `path_string`.
223 // Public for rustfmt usage.
224 pub fn submod_path_from_attr(
228 ) -> Option<PathBuf> {
229 // Extract path string from first `#[path = "path_string"]` attribute.
230 let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?;
231 let path_string = path_string.as_str();
233 // On windows, the base path might have the form
234 // `\\?\foo\bar` in which case it does not tolerate
235 // mixed `/` and `\` separators, so canonicalize
238 let path_string = path_string.replace("/", "\\");
240 Some(dir_path.join(&*path_string))
243 /// Returns a path to a module.
244 // Public for rustfmt usage.
245 pub fn default_submod_path<'a>(
249 relative: Option<Ident>,
251 ) -> ModulePath<'a> {
252 // If we're in a foo.rs file instead of a mod.rs file,
253 // we need to look for submodules in
254 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
255 // `./<id>.rs` and `./<id>/mod.rs`.
256 let relative_prefix_string;
257 let relative_prefix = if let Some(ident) = relative {
258 relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
259 &relative_prefix_string
264 let mod_name = id.name.to_string();
265 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
266 let secondary_path_str =
267 format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
268 let default_path = dir_path.join(&default_path_str);
269 let secondary_path = dir_path.join(&secondary_path_str);
270 let default_exists = sess.source_map().file_exists(&default_path);
271 let secondary_exists = sess.source_map().file_exists(&secondary_path);
273 let result = match (default_exists, secondary_exists) {
274 (true, false) => Ok(ModulePathSuccess {
276 ownership: DirectoryOwnership::Owned { relative: Some(id) },
278 (false, true) => Ok(ModulePathSuccess {
279 path: secondary_path,
280 ownership: DirectoryOwnership::Owned { relative: None },
283 let mut err = struct_span_err!(
284 sess.span_diagnostic,
287 "file not found for module `{}`",
291 "to create the module `{}`, create file \"{}\"",
293 default_path.display(),
298 let mut err = struct_span_err!(
299 sess.span_diagnostic,
302 "file for module `{}` found at both {} and {}",
307 err.help("delete or rename one of them to remove the ambiguity");
312 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }