]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/module.rs
Rollup merge of #82269 - LeSeulArtichaut:cleanup-ppmode, r=spastorino
[rust.git] / compiler / rustc_expand / src / module.rs
1 use rustc_ast::ptr::P;
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};
9
10 use std::path::{self, Path, PathBuf};
11
12 #[derive(Clone)]
13 pub struct Directory {
14     pub path: PathBuf,
15     pub ownership: DirectoryOwnership,
16 }
17
18 #[derive(Copy, Clone)]
19 pub enum DirectoryOwnership {
20     Owned {
21         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
22         relative: Option<Ident>,
23     },
24     UnownedViaBlock,
25     UnownedViaMod,
26 }
27
28 /// Information about the path to a module.
29 // Public for rustfmt usage.
30 pub struct ModulePath<'a> {
31     name: String,
32     path_exists: bool,
33     pub result: PResult<'a, ModulePathSuccess>,
34 }
35
36 // Public for rustfmt usage.
37 pub struct ModulePathSuccess {
38     pub path: PathBuf,
39     pub ownership: DirectoryOwnership,
40 }
41
42 crate fn parse_external_mod(
43     sess: &Session,
44     id: Ident,
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;
55
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);
62
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);
67         (items, inner_span)
68     };
69     // (1) ...instead, we return a dummy module.
70     let (items, inner_span) = result.map_err(|mut err| err.emit()).unwrap_or_default();
71
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()),
77     };
78     path.pop();
79
80     (items, inner_span, 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     sess: &Session,
103     id: Ident,
104     attrs: &[Attribute],
105     Directory { mut ownership, mut path }: Directory,
106 ) -> 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 };
110     } else {
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.
114         //
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());
121             }
122         }
123         path.push(&*id.as_str());
124     }
125     Directory { ownership, path }
126 }
127
128 fn submod_path<'a>(
129     sess: &'a Session,
130     id: Ident,
131     span: Span,
132     attrs: &[Attribute],
133     ownership: DirectoryOwnership,
134     dir_path: &Path,
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,
141             //
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,
147         };
148         return Ok(ModulePathSuccess { ownership, path });
149     }
150
151     let relative = match ownership {
152         DirectoryOwnership::Owned { relative } => relative,
153         DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
154     };
155     let ModulePath { path_exists, name, result } =
156         default_submod_path(&sess.parse_sess, id, span, relative, dir_path);
157     match ownership {
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)
162         }
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)
166         }
167     }
168 }
169
170 fn error_decl_mod_in_block<'a, T>(
171     sess: &'a ParseSess,
172     span: Span,
173     path_exists: bool,
174     name: &str,
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);
178     if path_exists {
179         let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
180         err.span_note(span, &msg);
181     }
182     Err(err)
183 }
184
185 fn error_cannot_declare_mod_here<'a, T>(
186     sess: &'a ParseSess,
187     span: Span,
188     path_exists: bool,
189     name: &str,
190 ) -> PResult<'a, T> {
191     let mut err =
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");
200                 err.span_note(
201                     span,
202                     &format!(
203                         "maybe move this module `{}` to its own directory via `{}`",
204                         src_path.display(),
205                         dest_path.display()
206                     ),
207                 );
208             }
209         }
210     }
211     if path_exists {
212         err.span_note(
213             span,
214             &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
215         );
216     }
217     Err(err)
218 }
219
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(
223     sess: &Session,
224     attrs: &[Attribute],
225     dir_path: &Path,
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();
230
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
234     // `/` to `\`.
235     #[cfg(windows)]
236     let path_string = path_string.replace("/", "\\");
237
238     Some(dir_path.join(&*path_string))
239 }
240
241 /// Returns a path to a module.
242 // Public for rustfmt usage.
243 pub fn default_submod_path<'a>(
244     sess: &'a ParseSess,
245     id: Ident,
246     span: Span,
247     relative: Option<Ident>,
248     dir_path: &Path,
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
258     } else {
259         ""
260     };
261
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);
270
271     let result = match (default_exists, secondary_exists) {
272         (true, false) => Ok(ModulePathSuccess {
273             path: default_path,
274             ownership: DirectoryOwnership::Owned { relative: Some(id) },
275         }),
276         (false, true) => Ok(ModulePathSuccess {
277             path: secondary_path,
278             ownership: DirectoryOwnership::Owned { relative: None },
279         }),
280         (false, false) => {
281             let mut err = struct_span_err!(
282                 sess.span_diagnostic,
283                 span,
284                 E0583,
285                 "file not found for module `{}`",
286                 mod_name,
287             );
288             err.help(&format!(
289                 "to create the module `{}`, create file \"{}\"",
290                 mod_name,
291                 default_path.display(),
292             ));
293             Err(err)
294         }
295         (true, true) => {
296             let mut err = struct_span_err!(
297                 sess.span_diagnostic,
298                 span,
299                 E0761,
300                 "file for module `{}` found at both {} and {}",
301                 mod_name,
302                 default_path_str,
303                 secondary_path_str,
304             );
305             err.help("delete or rename one of them to remove the ambiguity");
306             Err(err)
307         }
308     };
309
310     ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
311 }