]> git.proxmox.com Git - rustc.git/blob - vendor/rustc-ap-rustc_expand/src/module.rs
New upstream version 1.52.1+dfsg1
[rustc.git] / vendor / rustc-ap-rustc_expand / src / module.rs
1 use rustc_ast::{token, Attribute, Mod, Unsafe};
2 use rustc_errors::{struct_span_err, PResult};
3 use rustc_parse::new_parser_from_file;
4 use rustc_session::parse::ParseSess;
5 use rustc_session::Session;
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: &Session,
43 id: Ident,
44 span: Span, // The span to blame on errors.
45 unsafety: Unsafe,
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 parser = new_parser_from_file(&sess.parse_sess, &mp.path, Some(span));
65 let mut module = parser.parse_mod(&token::Eof, unsafety)?;
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_else(|_| {
71 let module = Mod { inner: Span::default(), unsafety, items: Vec::new(), inline: false };
72 (module, Vec::new())
73 });
74 attrs.append(&mut new_attrs);
75
76 // Extract the directory path for submodules of `module`.
77 let path = sess.source_map().span_to_unmapped_path(module.inner);
78 let mut path = match path {
79 FileName::Real(name) => name.into_local_path(),
80 other => PathBuf::from(other.to_string()),
81 };
82 path.pop();
83
84 (module, Directory { ownership, path })
85 }
86
87 fn error_on_circular_module<'a>(
88 sess: &'a ParseSess,
89 span: Span,
90 path: &Path,
91 included_mod_stack: &[PathBuf],
92 ) -> PResult<'a, ()> {
93 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
94 let mut err = String::from("circular modules: ");
95 for p in &included_mod_stack[i..] {
96 err.push_str(&p.to_string_lossy());
97 err.push_str(" -> ");
98 }
99 err.push_str(&path.to_string_lossy());
100 return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
101 }
102 Ok(())
103 }
104
105 crate fn push_directory(
106 sess: &Session,
107 id: Ident,
108 attrs: &[Attribute],
109 Directory { mut ownership, mut path }: Directory,
110 ) -> Directory {
111 if let Some(filename) = sess.first_attr_value_str_by_name(attrs, sym::path) {
112 path.push(&*filename.as_str());
113 ownership = DirectoryOwnership::Owned { relative: None };
114 } else {
115 // We have to push on the current module name in the case of relative
116 // paths in order to ensure that any additional module paths from inline
117 // `mod x { ... }` come after the relative extension.
118 //
119 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
120 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
121 if let DirectoryOwnership::Owned { relative } = &mut ownership {
122 if let Some(ident) = relative.take() {
123 // Remove the relative offset.
124 path.push(&*ident.as_str());
125 }
126 }
127 path.push(&*id.as_str());
128 }
129 Directory { ownership, path }
130 }
131
132 fn submod_path<'a>(
133 sess: &'a Session,
134 id: Ident,
135 span: Span,
136 attrs: &[Attribute],
137 ownership: DirectoryOwnership,
138 dir_path: &Path,
139 ) -> PResult<'a, ModulePathSuccess> {
140 if let Some(path) = submod_path_from_attr(sess, attrs, dir_path) {
141 let ownership = match path.file_name().and_then(|s| s.to_str()) {
142 // All `#[path]` files are treated as though they are a `mod.rs` file.
143 // This means that `mod foo;` declarations inside `#[path]`-included
144 // files are siblings,
145 //
146 // Note that this will produce weirdness when a file named `foo.rs` is
147 // `#[path]` included and contains a `mod foo;` declaration.
148 // If you encounter this, it's your own darn fault :P
149 Some(_) => DirectoryOwnership::Owned { relative: None },
150 _ => DirectoryOwnership::UnownedViaMod,
151 };
152 return Ok(ModulePathSuccess { ownership, path });
153 }
154
155 let relative = match ownership {
156 DirectoryOwnership::Owned { relative } => relative,
157 DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None,
158 };
159 let ModulePath { path_exists, name, result } =
160 default_submod_path(&sess.parse_sess, id, span, relative, dir_path);
161 match ownership {
162 DirectoryOwnership::Owned { .. } => Ok(result?),
163 DirectoryOwnership::UnownedViaBlock => {
164 let _ = result.map_err(|mut err| err.cancel());
165 error_decl_mod_in_block(&sess.parse_sess, span, path_exists, &name)
166 }
167 DirectoryOwnership::UnownedViaMod => {
168 let _ = result.map_err(|mut err| err.cancel());
169 error_cannot_declare_mod_here(&sess.parse_sess, span, path_exists, &name)
170 }
171 }
172 }
173
174 fn error_decl_mod_in_block<'a, T>(
175 sess: &'a ParseSess,
176 span: Span,
177 path_exists: bool,
178 name: &str,
179 ) -> PResult<'a, T> {
180 let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
181 let mut err = sess.span_diagnostic.struct_span_err(span, msg);
182 if path_exists {
183 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
184 err.span_note(span, &msg);
185 }
186 Err(err)
187 }
188
189 fn error_cannot_declare_mod_here<'a, T>(
190 sess: &'a ParseSess,
191 span: Span,
192 path_exists: bool,
193 name: &str,
194 ) -> PResult<'a, T> {
195 let mut err =
196 sess.span_diagnostic.struct_span_err(span, "cannot declare a new module at this location");
197 if !span.is_dummy() {
198 if let FileName::Real(src_name) = sess.source_map().span_to_filename(span) {
199 let src_path = src_name.into_local_path();
200 if let Some(stem) = src_path.file_stem() {
201 let mut dest_path = src_path.clone();
202 dest_path.set_file_name(stem);
203 dest_path.push("mod.rs");
204 err.span_note(
205 span,
206 &format!(
207 "maybe move this module `{}` to its own directory via `{}`",
208 src_path.display(),
209 dest_path.display()
210 ),
211 );
212 }
213 }
214 }
215 if path_exists {
216 err.span_note(
217 span,
218 &format!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name),
219 );
220 }
221 Err(err)
222 }
223
224 /// Derive a submodule path from the first found `#[path = "path_string"]`.
225 /// The provided `dir_path` is joined with the `path_string`.
226 pub(super) fn submod_path_from_attr(
227 sess: &Session,
228 attrs: &[Attribute],
229 dir_path: &Path,
230 ) -> Option<PathBuf> {
231 // Extract path string from first `#[path = "path_string"]` attribute.
232 let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?;
233 let path_string = path_string.as_str();
234
235 // On windows, the base path might have the form
236 // `\\?\foo\bar` in which case it does not tolerate
237 // mixed `/` and `\` separators, so canonicalize
238 // `/` to `\`.
239 #[cfg(windows)]
240 let path_string = path_string.replace("/", "\\");
241
242 Some(dir_path.join(&*path_string))
243 }
244
245 /// Returns a path to a module.
246 // Public for rustfmt usage.
247 pub fn default_submod_path<'a>(
248 sess: &'a ParseSess,
249 id: Ident,
250 span: Span,
251 relative: Option<Ident>,
252 dir_path: &Path,
253 ) -> ModulePath<'a> {
254 // If we're in a foo.rs file instead of a mod.rs file,
255 // we need to look for submodules in
256 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
257 // `./<id>.rs` and `./<id>/mod.rs`.
258 let relative_prefix_string;
259 let relative_prefix = if let Some(ident) = relative {
260 relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
261 &relative_prefix_string
262 } else {
263 ""
264 };
265
266 let mod_name = id.name.to_string();
267 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
268 let secondary_path_str =
269 format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
270 let default_path = dir_path.join(&default_path_str);
271 let secondary_path = dir_path.join(&secondary_path_str);
272 let default_exists = sess.source_map().file_exists(&default_path);
273 let secondary_exists = sess.source_map().file_exists(&secondary_path);
274
275 let result = match (default_exists, secondary_exists) {
276 (true, false) => Ok(ModulePathSuccess {
277 path: default_path,
278 ownership: DirectoryOwnership::Owned { relative: Some(id) },
279 }),
280 (false, true) => Ok(ModulePathSuccess {
281 path: secondary_path,
282 ownership: DirectoryOwnership::Owned { relative: None },
283 }),
284 (false, false) => {
285 let mut err = struct_span_err!(
286 sess.span_diagnostic,
287 span,
288 E0583,
289 "file not found for module `{}`",
290 mod_name,
291 );
292 err.help(&format!(
293 "to create the module `{}`, create file \"{}\"",
294 mod_name,
295 default_path.display(),
296 ));
297 Err(err)
298 }
299 (true, true) => {
300 let mut err = struct_span_err!(
301 sess.span_diagnostic,
302 span,
303 E0761,
304 "file for module `{}` found at both {} and {}",
305 mod_name,
306 default_path_str,
307 secondary_path_str,
308 );
309 err.help("delete or rename one of them to remove the ambiguity");
310 Err(err)
311 }
312 };
313
314 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
315 }