]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/module.rs
Auto merge of #75137 - Aaron1011:fix/hygiene-skip-expndata, r=petrochenkov
[rust.git] / src / librustc_expand / module.rs
1 use rustc_ast::ast::{Attribute, Mod};
2 use rustc_ast::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_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 ) -> (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;
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 module =
65             new_parser_from_file(&sess.parse_sess, &mp.path, Some(span)).parse_mod(&token::Eof)?;
66         module.0.inline = false;
67         module
68     };
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);
72
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()),
78     };
79     path.pop();
80
81     (module, Directory { ownership, path })
82 }
83
84 fn error_on_circular_module<'a>(
85     sess: &'a ParseSess,
86     span: Span,
87     path: &Path,
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());
94             err.push_str(" -> ");
95         }
96         err.push_str(&path.to_string_lossy());
97         return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
98     }
99     Ok(())
100 }
101
102 crate fn push_directory(
103     sess: &Session,
104     id: Ident,
105     attrs: &[Attribute],
106     Directory { mut ownership, mut path }: Directory,
107 ) -> 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 };
111     } else {
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.
115         //
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());
122             }
123         }
124         path.push(&*id.as_str());
125     }
126     Directory { ownership, path }
127 }
128
129 fn submod_path<'a>(
130     sess: &'a Session,
131     id: Ident,
132     span: Span,
133     attrs: &[Attribute],
134     ownership: DirectoryOwnership,
135     dir_path: &Path,
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,
142             //
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,
148         };
149         return Ok(ModulePathSuccess { ownership, path });
150     }
151
152     let relative = match ownership {
153         DirectoryOwnership::Owned { relative } => relative,
154         DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
155     };
156     let ModulePath { path_exists, name, result } =
157         default_submod_path(&sess.parse_sess, id, span, relative, dir_path);
158     match ownership {
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)
163         }
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)
167         }
168     }
169 }
170
171 fn error_decl_mod_in_block<'a, T>(
172     sess: &'a ParseSess,
173     span: Span,
174     path_exists: bool,
175     name: &str,
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);
179     if path_exists {
180         let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
181         err.span_note(span, &msg);
182     }
183     Err(err)
184 }
185
186 fn error_cannot_declare_mod_here<'a, T>(
187     sess: &'a ParseSess,
188     span: Span,
189     path_exists: bool,
190     name: &str,
191 ) -> PResult<'a, T> {
192     let mut err =
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");
201                 err.span_note(
202                     span,
203                     &format!(
204                         "maybe move this module `{}` to its own directory via `{}`",
205                         src_path.display(),
206                         dest_path.display()
207                     ),
208                 );
209             }
210         }
211     }
212     if path_exists {
213         err.span_note(
214             span,
215             &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
216         );
217     }
218     Err(err)
219 }
220
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(
225     sess: &Session,
226     attrs: &[Attribute],
227     dir_path: &Path,
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();
232
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
236     // `/` to `\`.
237     #[cfg(windows)]
238     let path_string = path_string.replace("/", "\\");
239
240     Some(dir_path.join(&*path_string))
241 }
242
243 /// Returns a path to a module.
244 // Public for rustfmt usage.
245 pub fn default_submod_path<'a>(
246     sess: &'a ParseSess,
247     id: Ident,
248     span: Span,
249     relative: Option<Ident>,
250     dir_path: &Path,
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
260     } else {
261         ""
262     };
263
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);
272
273     let result = match (default_exists, secondary_exists) {
274         (true, false) => Ok(ModulePathSuccess {
275             path: default_path,
276             ownership: DirectoryOwnership::Owned { relative: Some(id) },
277         }),
278         (false, true) => Ok(ModulePathSuccess {
279             path: secondary_path,
280             ownership: DirectoryOwnership::Owned { relative: None },
281         }),
282         (false, false) => {
283             let mut err = struct_span_err!(
284                 sess.span_diagnostic,
285                 span,
286                 E0583,
287                 "file not found for module `{}`",
288                 mod_name,
289             );
290             err.help(&format!(
291                 "to create the module `{}`, create file \"{}\"",
292                 mod_name,
293                 default_path.display(),
294             ));
295             Err(err)
296         }
297         (true, true) => {
298             let mut err = struct_span_err!(
299                 sess.span_diagnostic,
300                 span,
301                 E0761,
302                 "file for module `{}` found at both {} and {}",
303                 mod_name,
304                 default_path_str,
305                 secondary_path_str,
306             );
307             err.help("delete or rename one of them to remove the ambiguity");
308             Err(err)
309         }
310     };
311
312     ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
313 }