]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/module.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_expand / module.rs
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;
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<ast::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: ast::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 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;
66         module
67     };
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);
71
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()),
77     };
78     path.pop();
79
80     (module, Directory { ownership, path })
81 }
82
83 fn error_on_circular_module<'a>(
84     sess: &'a ParseSess,
85     span: Span,
86     path: &Path,
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());
93             err.push_str(" -> ");
94         }
95         err.push_str(&path.to_string_lossy());
96         return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
97     }
98     Ok(())
99 }
100
101 crate fn push_directory(
102     id: Ident,
103     attrs: &[Attribute],
104     Directory { mut ownership, mut path }: Directory,
105 ) -> 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 };
109     } else {
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.
113         //
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());
120             }
121         }
122         path.push(&*id.as_str());
123     }
124     Directory { ownership, path }
125 }
126
127 fn submod_path<'a>(
128     sess: &'a ParseSess,
129     id: ast::Ident,
130     span: Span,
131     attrs: &[Attribute],
132     ownership: DirectoryOwnership,
133     dir_path: &Path,
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,
140             //
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,
146         };
147         return Ok(ModulePathSuccess { ownership, path });
148     }
149
150     let relative = match ownership {
151         DirectoryOwnership::Owned { relative } => relative,
152         DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
153     };
154     let ModulePath { path_exists, name, result } =
155         default_submod_path(sess, id, span, relative, dir_path);
156     match ownership {
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)
161         }
162         DirectoryOwnership::UnownedViaMod => {
163             let _ = result.map_err(|mut err| err.cancel());
164             error_cannot_declare_mod_here(sess, span, path_exists, &name)
165         }
166     }
167 }
168
169 fn error_decl_mod_in_block<'a, T>(
170     sess: &'a ParseSess,
171     span: Span,
172     path_exists: bool,
173     name: &str,
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);
177     if path_exists {
178         let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
179         err.span_note(span, &msg);
180     }
181     Err(err)
182 }
183
184 fn error_cannot_declare_mod_here<'a, T>(
185     sess: &'a ParseSess,
186     span: Span,
187     path_exists: bool,
188     name: &str,
189 ) -> PResult<'a, T> {
190     let mut err =
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");
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: ast::Ident,
241     span: Span,
242     relative: Option<ast::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                 E0584,
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 }