]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/module.rs
expand: Some more consistent naming in module loading
[rust.git] / compiler / rustc_expand / src / module.rs
1 use crate::base::ModuleData;
2 use rustc_ast::ptr::P;
3 use rustc_ast::{token, Attribute, Item};
4 use rustc_errors::{struct_span_err, PResult};
5 use rustc_parse::new_parser_from_file;
6 use rustc_session::parse::ParseSess;
7 use rustc_session::Session;
8 use rustc_span::symbol::{sym, Ident};
9 use rustc_span::Span;
10
11 use std::path::{self, Path, PathBuf};
12
13 #[derive(Copy, Clone)]
14 pub enum DirOwnership {
15     Owned {
16         // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
17         relative: Option<Ident>,
18     },
19     UnownedViaBlock,
20 }
21
22 /// Information about the path to a module.
23 // Public for rustfmt usage.
24 pub struct ModulePath<'a> {
25     name: String,
26     path_exists: bool,
27     pub result: PResult<'a, ModulePathSuccess>,
28 }
29
30 // Public for rustfmt usage.
31 pub struct ModulePathSuccess {
32     pub file_path: PathBuf,
33     pub dir_ownership: DirOwnership,
34 }
35
36 crate struct ParsedExternalMod {
37     pub items: Vec<P<Item>>,
38     pub inner_span: Span,
39     pub file_path: PathBuf,
40     pub dir_path: PathBuf,
41     pub dir_ownership: DirOwnership,
42 }
43
44 crate fn parse_external_mod(
45     sess: &Session,
46     ident: Ident,
47     span: Span, // The span to blame on errors.
48     module: &ModuleData,
49     mut dir_ownership: DirOwnership,
50     attrs: &mut Vec<Attribute>,
51 ) -> ParsedExternalMod {
52     // We bail on the first error, but that error does not cause a fatal error... (1)
53     let result: PResult<'_, _> = try {
54         // Extract the file path and the new ownership.
55         let mp = mod_file_path(sess, ident, span, &attrs, &module.dir_path, dir_ownership)?;
56         dir_ownership = mp.dir_ownership;
57
58         // Ensure file paths are acyclic.
59         error_on_circular_module(&sess.parse_sess, span, &mp.file_path, &module.file_path_stack)?;
60
61         // Actually parse the external file as a module.
62         let mut parser = new_parser_from_file(&sess.parse_sess, &mp.file_path, Some(span));
63         let (mut inner_attrs, items, inner_span) = parser.parse_mod(&token::Eof)?;
64         attrs.append(&mut inner_attrs);
65         (items, inner_span, mp.file_path)
66     };
67     // (1) ...instead, we return a dummy module.
68     let (items, inner_span, file_path) = result.map_err(|mut err| err.emit()).unwrap_or_default();
69
70     // Extract the directory path for submodules of the module.
71     let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
72
73     ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership }
74 }
75
76 fn error_on_circular_module<'a>(
77     sess: &'a ParseSess,
78     span: Span,
79     file_path: &Path,
80     file_path_stack: &[PathBuf],
81 ) -> PResult<'a, ()> {
82     if let Some(i) = file_path_stack.iter().position(|p| *p == file_path) {
83         let mut err = String::from("circular modules: ");
84         for p in &file_path_stack[i..] {
85             err.push_str(&p.to_string_lossy());
86             err.push_str(" -> ");
87         }
88         err.push_str(&file_path.to_string_lossy());
89         return Err(sess.span_diagnostic.struct_span_err(span, &err[..]));
90     }
91     Ok(())
92 }
93
94 crate fn mod_dir_path(
95     sess: &Session,
96     ident: Ident,
97     attrs: &[Attribute],
98     module: &ModuleData,
99     mut dir_ownership: DirOwnership,
100 ) -> (PathBuf, DirOwnership) {
101     let mut dir_path = module.dir_path.clone();
102     if let Some(file_path) = sess.first_attr_value_str_by_name(attrs, sym::path) {
103         dir_path.push(&*file_path.as_str());
104         dir_ownership = DirOwnership::Owned { relative: None };
105     } else {
106         // We have to push on the current module name in the case of relative
107         // paths in order to ensure that any additional module paths from inline
108         // `mod x { ... }` come after the relative extension.
109         //
110         // For example, a `mod z { ... }` inside `x/y.rs` should set the current
111         // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
112         if let DirOwnership::Owned { relative } = &mut dir_ownership {
113             if let Some(ident) = relative.take() {
114                 // Remove the relative offset.
115                 dir_path.push(&*ident.as_str());
116             }
117         }
118         dir_path.push(&*ident.as_str());
119     }
120
121     (dir_path, dir_ownership)
122 }
123
124 fn mod_file_path<'a>(
125     sess: &'a Session,
126     ident: Ident,
127     span: Span,
128     attrs: &[Attribute],
129     dir_path: &Path,
130     dir_ownership: DirOwnership,
131 ) -> PResult<'a, ModulePathSuccess> {
132     if let Some(file_path) = mod_file_path_from_attr(sess, attrs, dir_path) {
133         // All `#[path]` files are treated as though they are a `mod.rs` file.
134         // This means that `mod foo;` declarations inside `#[path]`-included
135         // files are siblings,
136         //
137         // Note that this will produce weirdness when a file named `foo.rs` is
138         // `#[path]` included and contains a `mod foo;` declaration.
139         // If you encounter this, it's your own darn fault :P
140         let dir_ownership = DirOwnership::Owned { relative: None };
141         return Ok(ModulePathSuccess { file_path, dir_ownership });
142     }
143
144     let relative = match dir_ownership {
145         DirOwnership::Owned { relative } => relative,
146         DirOwnership::UnownedViaBlock => None,
147     };
148     let ModulePath { path_exists, name, result } =
149         default_submod_path(&sess.parse_sess, ident, span, relative, dir_path);
150     match dir_ownership {
151         DirOwnership::Owned { .. } => Ok(result?),
152         DirOwnership::UnownedViaBlock => {
153             let _ = result.map_err(|mut err| err.cancel());
154             error_decl_mod_in_block(&sess.parse_sess, span, path_exists, &name)
155         }
156     }
157 }
158
159 fn error_decl_mod_in_block<'a, T>(
160     sess: &'a ParseSess,
161     span: Span,
162     path_exists: bool,
163     name: &str,
164 ) -> PResult<'a, T> {
165     let msg = "Cannot declare a non-inline module inside a block unless it has a path attribute";
166     let mut err = sess.span_diagnostic.struct_span_err(span, msg);
167     if path_exists {
168         let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", name);
169         err.span_note(span, &msg);
170     }
171     Err(err)
172 }
173
174 /// Derive a submodule path from the first found `#[path = "path_string"]`.
175 /// The provided `dir_path` is joined with the `path_string`.
176 fn mod_file_path_from_attr(
177     sess: &Session,
178     attrs: &[Attribute],
179     dir_path: &Path,
180 ) -> Option<PathBuf> {
181     // Extract path string from first `#[path = "path_string"]` attribute.
182     let path_string = sess.first_attr_value_str_by_name(attrs, sym::path)?;
183     let path_string = path_string.as_str();
184
185     // On windows, the base path might have the form
186     // `\\?\foo\bar` in which case it does not tolerate
187     // mixed `/` and `\` separators, so canonicalize
188     // `/` to `\`.
189     #[cfg(windows)]
190     let path_string = path_string.replace("/", "\\");
191
192     Some(dir_path.join(&*path_string))
193 }
194
195 /// Returns a path to a module.
196 // Public for rustfmt usage.
197 pub fn default_submod_path<'a>(
198     sess: &'a ParseSess,
199     ident: Ident,
200     span: Span,
201     relative: Option<Ident>,
202     dir_path: &Path,
203 ) -> ModulePath<'a> {
204     // If we're in a foo.rs file instead of a mod.rs file,
205     // we need to look for submodules in
206     // `./foo/<ident>.rs` and `./foo/<ident>/mod.rs` rather than
207     // `./<ident>.rs` and `./<ident>/mod.rs`.
208     let relative_prefix_string;
209     let relative_prefix = if let Some(ident) = relative {
210         relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
211         &relative_prefix_string
212     } else {
213         ""
214     };
215
216     let mod_name = ident.name.to_string();
217     let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
218     let secondary_path_str =
219         format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR);
220     let default_path = dir_path.join(&default_path_str);
221     let secondary_path = dir_path.join(&secondary_path_str);
222     let default_exists = sess.source_map().file_exists(&default_path);
223     let secondary_exists = sess.source_map().file_exists(&secondary_path);
224
225     let result = match (default_exists, secondary_exists) {
226         (true, false) => Ok(ModulePathSuccess {
227             file_path: default_path,
228             dir_ownership: DirOwnership::Owned { relative: Some(ident) },
229         }),
230         (false, true) => Ok(ModulePathSuccess {
231             file_path: secondary_path,
232             dir_ownership: DirOwnership::Owned { relative: None },
233         }),
234         (false, false) => {
235             let mut err = struct_span_err!(
236                 sess.span_diagnostic,
237                 span,
238                 E0583,
239                 "file not found for module `{}`",
240                 mod_name,
241             );
242             err.help(&format!(
243                 "to create the module `{}`, create file \"{}\"",
244                 mod_name,
245                 default_path.display(),
246             ));
247             Err(err)
248         }
249         (true, true) => {
250             let mut err = struct_span_err!(
251                 sess.span_diagnostic,
252                 span,
253                 E0761,
254                 "file for module `{}` found at both {} and {}",
255                 mod_name,
256                 default_path_str,
257                 secondary_path_str,
258             );
259             err.help("delete or rename one of them to remove the ambiguity");
260             Err(err)
261         }
262     };
263
264     ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }
265 }