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}
;
9 use std
::path
::{self, Path, PathBuf}
;
12 pub struct Directory
{
14 pub ownership
: DirectoryOwnership
,
17 #[derive(Copy, Clone)]
18 pub enum DirectoryOwnership
{
20 // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
21 relative
: Option
<Ident
>,
27 /// Information about the path to a module.
28 // Public for rustfmt usage.
29 pub struct ModulePath
<'a
> {
32 pub result
: PResult
<'a
, ModulePathSuccess
>,
35 // Public for rustfmt usage.
36 pub struct ModulePathSuccess
{
38 pub ownership
: DirectoryOwnership
,
41 crate fn parse_external_mod(
44 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
;
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
);
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;
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 }
;
74 attrs
.append(&mut new_attrs
);
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()),
84 (module
, Directory { ownership, path }
)
87 fn error_on_circular_module
<'a
>(
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());
99 err
.push_str(&path
.to_string_lossy());
100 return Err(sess
.span_diagnostic
.struct_span_err(span
, &err
[..]));
105 crate fn push_directory(
109 Directory { mut ownership, mut path }
: 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 }
;
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.
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());
127 path
.push(&*id
.as_str());
129 Directory { ownership, path }
137 ownership
: DirectoryOwnership
,
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,
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
,
152 return Ok(ModulePathSuccess { ownership, path }
);
155 let relative
= match ownership
{
156 DirectoryOwnership
::Owned { relative }
=> relative
,
157 DirectoryOwnership
::UnownedViaBlock
| DirectoryOwnership
::UnownedViaMod
=> None
,
159 let ModulePath { path_exists, name, result }
=
160 default_submod_path(&sess
.parse_sess
, id
, span
, relative
, dir_path
);
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
)
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
)
174 fn error_decl_mod_in_block
<'a
, T
>(
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
);
183 let msg
= format
!("Maybe `use` the module `{}` instead of redeclaring it", name
);
184 err
.span_note(span
, &msg
);
189 fn error_cannot_declare_mod_here
<'a
, T
>(
194 ) -> PResult
<'a
, T
> {
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");
207 "maybe move this module `{}` to its own directory via `{}`",
218 &format
!("... or maybe `use` the module `{}` instead of possibly redeclaring it", name
),
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(
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();
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
240 let path_string
= path_string
.replace("/", "\\");
242 Some(dir_path
.join(&*path_string
))
245 /// Returns a path to a module.
246 // Public for rustfmt usage.
247 pub fn default_submod_path
<'a
>(
251 relative
: Option
<Ident
>,
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
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
);
275 let result
= match (default_exists
, secondary_exists
) {
276 (true, false) => Ok(ModulePathSuccess
{
278 ownership
: DirectoryOwnership
::Owned { relative: Some(id) }
,
280 (false, true) => Ok(ModulePathSuccess
{
281 path
: secondary_path
,
282 ownership
: DirectoryOwnership
::Owned { relative: None }
,
285 let mut err
= struct_span_err
!(
286 sess
.span_diagnostic
,
289 "file not found for module `{}`",
293 "to create the module `{}`, create file \"{}\"",
295 default_path
.display(),
300 let mut err
= struct_span_err
!(
301 sess
.span_diagnostic
,
304 "file for module `{}` found at both {} and {}",
309 err
.help("delete or rename one of them to remove the ambiguity");
314 ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result }