]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/module.rs
Merge branch 'master' into feature/incorporate-tracing
[rust.git] / src / librustc_expand / module.rs
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};
8
9 use std::path::{self, Path, PathBuf};
10
11 #[derive(Clone)]
12 pub struct Directory {
13     pub path: PathBuf,
14     pub ownership: DirectoryOwnership,
15 }
16
17 #[derive(Copy, Clone)]
18 pub enum DirectoryOwnership {
19     Owned {
20         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
21         relative: Option<Ident>,
22     },
23     UnownedViaBlock,
24     UnownedViaMod,
25 }
26
27 /// Information about the path to a module.
28 // Public for rustfmt usage.
29 pub struct ModulePath<'a> {
30     name: String,
31     path_exists: bool,
32     pub result: PResult<'a, ModulePathSuccess>,
33 }
34
35 // Public for rustfmt usage.
36 pub struct ModulePathSuccess {
37     pub path: PathBuf,
38     pub ownership: DirectoryOwnership,
39 }
40
41 crate fn parse_external_mod(
42     sess: &ParseSess,
43     id: Ident,
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;
54
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);
61
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;
65         module
66     };
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);
70
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()),
76     };
77     path.pop();
78
79     (module, Directory { ownership, path })
80 }
81
82 fn error_on_circular_module<'a>(
83     sess: &'a ParseSess,
84     span: Span,
85     path: &Path,
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());
92             err.push_str(" -> ");
93         }
94         err.push_str(&path.to_string_lossy());
95         return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
96     }
97     Ok(())
98 }
99
100 crate fn push_directory(
101     id: Ident,
102     attrs: &[Attribute],
103     Directory { mut ownership, mut path }: Directory,
104 ) -> 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 };
108     } else {
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.
112         //
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());
119             }
120         }
121         path.push(&*id.as_str());
122     }
123     Directory { ownership, path }
124 }
125
126 fn submod_path<'a>(
127     sess: &'a ParseSess,
128     id: Ident,
129     span: Span,
130     attrs: &[Attribute],
131     ownership: DirectoryOwnership,
132     dir_path: &Path,
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,
139             //
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,
145         };
146         return Ok(ModulePathSuccess { ownership, path });
147     }
148
149     let relative = match ownership {
150         DirectoryOwnership::Owned { relative } => relative,
151         DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
152     };
153     let ModulePath { path_exists, name, result } =
154         default_submod_path(sess, id, span, relative, dir_path);
155     match ownership {
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)
160         }
161         DirectoryOwnership::UnownedViaMod => {
162             let _ = result.map_err(|mut err| err.cancel());
163             error_cannot_declare_mod_here(sess, span, path_exists, &name)
164         }
165     }
166 }
167
168 fn error_decl_mod_in_block<'a, T>(
169     sess: &'a ParseSess,
170     span: Span,
171     path_exists: bool,
172     name: &str,
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);
176     if path_exists {
177         let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
178         err.span_note(span, &msg);
179     }
180     Err(err)
181 }
182
183 fn error_cannot_declare_mod_here<'a, T>(
184     sess: &'a ParseSess,
185     span: Span,
186     path_exists: bool,
187     name: &str,
188 ) -> PResult<'a, T> {
189     let mut err =
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");
198                 err.span_note(
199                     span,
200                     &format!(
201                         "maybe move this module `{}` to its own directory via `{}`",
202                         src_path.display(),
203                         dest_path.display()
204                     ),
205                 );
206             }
207         }
208     }
209     if path_exists {
210         err.span_note(
211             span,
212             &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
213         );
214     }
215     Err(err)
216 }
217
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();
225
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
229     // `/` to `\`.
230     #[cfg(windows)]
231     let path_string = path_string.replace("/", "\\");
232
233     Some(dir_path.join(&*path_string))
234 }
235
236 /// Returns a path to a module.
237 // Public for rustfmt usage.
238 pub fn default_submod_path<'a>(
239     sess: &'a ParseSess,
240     id: Ident,
241     span: Span,
242     relative: Option<Ident>,
243     dir_path: &Path,
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
253     } else {
254         ""
255     };
256
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);
265
266     let result = match (default_exists, secondary_exists) {
267         (true, false) => Ok(ModulePathSuccess {
268             path: default_path,
269             ownership: DirectoryOwnership::Owned { relative: Some(id) },
270         }),
271         (false, true) => Ok(ModulePathSuccess {
272             path: secondary_path,
273             ownership: DirectoryOwnership::Owned { relative: None },
274         }),
275         (false, false) => {
276             let mut err = struct_span_err!(
277                 sess.span_diagnostic,
278                 span,
279                 E0583,
280                 "file not found for module `{}`",
281                 mod_name,
282             );
283             err.help(&format!(
284                 "to create the module `{}`, create file \"{}\"",
285                 mod_name,
286                 default_path.display(),
287             ));
288             Err(err)
289         }
290         (true, true) => {
291             let mut err = struct_span_err!(
292                 sess.span_diagnostic,
293                 span,
294                 E0761,
295                 "file for module `{}` found at both {} and {}",
296                 mod_name,
297                 default_path_str,
298                 secondary_path_str,
299             );
300             err.help("delete or rename one of them to remove the ambiguity");
301             Err(err)
302         }
303     };
304
305     ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
306 }