1 use rustc_ast::ast::{Attribute, Mod};
2 use rustc_ast::{attr, token};
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_span::source_map::{FileName, Span};
7 use rustc_span::symbol::{sym, Ident};
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<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 a module.
63 let mut module = new_parser_from_file(sess, &mp.path, Some(span)).parse_mod(&token::Eof)?;
64 module.0.inline = false;
67 // (1) ...instead, we return a dummy module.
68 let (module, mut new_attrs) = result.map_err(|mut err| err.emit()).unwrap_or_default();
69 attrs.append(&mut new_attrs);
71 // Extract the directory path for submodules of `module`.
72 let path = sess.source_map().span_to_unmapped_path(module.inner);
73 let mut path = match path {
74 FileName::Real(name) => name.into_local_path(),
75 other => PathBuf::from(other.to_string()),
79 (module, Directory { ownership, path })
82 fn error_on_circular_module<'a>(
86 included_mod_stack: &[PathBuf],
87 ) -> PResult<'a, ()> {
88 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
89 let mut err = String::from("circular modules: ");
90 for p in &included_mod_stack[i..] {
91 err.push_str(&p.to_string_lossy());
94 err.push_str(&path.to_string_lossy());
95 return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
100 crate fn push_directory(
103 Directory { mut ownership, mut path }: Directory,
105 if let Some(filename) = attr::first_attr_value_str_by_name(attrs, sym::path) {
106 path.push(&*filename.as_str());
107 ownership = DirectoryOwnership::Owned { relative: None };
109 // We have to push on the current module name in the case of relative
110 // paths in order to ensure that any additional module paths from inline
111 // `mod x { ... }` come after the relative extension.
113 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
114 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
115 if let DirectoryOwnership::Owned { relative } = &mut ownership {
116 if let Some(ident) = relative.take() {
117 // Remove the relative offset.
118 path.push(&*ident.as_str());
121 path.push(&*id.as_str());
123 Directory { ownership, path }
131 ownership: DirectoryOwnership,
133 ) -> PResult<'a, ModulePathSuccess> {
134 if let Some(path) = submod_path_from_attr(attrs, dir_path) {
135 let ownership = match path.file_name().and_then(|s| s.to_str()) {
136 // All `#[path]` files are treated as though they are a `mod.rs` file.
137 // This means that `mod foo;` declarations inside `#[path]`-included
138 // files are siblings,
140 // Note that this will produce weirdness when a file named `foo.rs` is
141 // `#[path]` included and contains a `mod foo;` declaration.
142 // If you encounter this, it's your own darn fault :P
143 Some(_) => DirectoryOwnership::Owned { relative: None },
144 _ => DirectoryOwnership::UnownedViaMod,
146 return Ok(ModulePathSuccess { ownership, path });
149 let relative = match ownership {
150 DirectoryOwnership::Owned { relative } => relative,
151 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
153 let ModulePath { path_exists, name, result } =
154 default_submod_path(sess, id, span, relative, dir_path);
156 DirectoryOwnership::Owned { .. } => Ok(result?),
157 DirectoryOwnership::UnownedViaBlock => {
158 let _ = result.map_err(|mut err| err.cancel());
159 error_decl_mod_in_block(sess, span, path_exists, &name)
161 DirectoryOwnership::UnownedViaMod => {
162 let _ = result.map_err(|mut err| err.cancel());
163 error_cannot_declare_mod_here(sess, span, path_exists, &name)
168 fn error_decl_mod_in_block<'a, T>(
173 ) -> PResult<'a, T> {
174 let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
175 let mut err = sess.span_diagnostic.struct_span_err(span, msg);
177 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
178 err.span_note(span, &msg);
183 fn error_cannot_declare_mod_here<'a, T>(
188 ) -> PResult<'a, T> {
190 sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
191 if !span.is_dummy() {
192 if let FileName::Real(src_name) = sess.source_map().span_to_filename(span) {
193 let src_path = src_name.into_local_path();
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<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 }