rustc_expand/
module.rs

1use std::iter::once;
2use std::path::{self, Path, PathBuf};
3
4use rustc_ast::{AttrVec, Attribute, Inline, Item, ModSpans};
5use rustc_attr_parsing::validate_attr;
6use rustc_errors::{Diag, ErrorGuaranteed};
7use rustc_parse::lexer::StripTokens;
8use rustc_parse::{exp, new_parser_from_file, unwrap_or_emit_fatal};
9use rustc_session::Session;
10use rustc_session::parse::ParseSess;
11use rustc_span::{Ident, Span, sym};
12use thin_vec::ThinVec;
13
14use crate::base::ModuleData;
15use crate::errors::{
16    ModuleCircular, ModuleFileNotFound, ModuleInBlock, ModuleInBlockName, ModuleMultipleCandidates,
17};
18
19#[derive(Copy, Clone)]
20pub enum DirOwnership {
21    Owned {
22        // None if `mod.rs`, `Some("foo")` if we're in `foo.rs`.
23        relative: Option<Ident>,
24    },
25    UnownedViaBlock,
26}
27
28// Public for rustfmt usage.
29pub struct ModulePathSuccess {
30    pub file_path: PathBuf,
31    pub dir_ownership: DirOwnership,
32}
33
34pub(crate) struct ParsedExternalMod {
35    pub items: ThinVec<Box<Item>>,
36    pub spans: ModSpans,
37    pub file_path: PathBuf,
38    pub dir_path: PathBuf,
39    pub dir_ownership: DirOwnership,
40    pub had_parse_error: Result<(), ErrorGuaranteed>,
41}
42
43pub enum ModError<'a> {
44    CircularInclusion(Vec<PathBuf>),
45    ModInBlock(Option<Ident>),
46    FileNotFound(Ident, PathBuf, PathBuf),
47    MultipleCandidates(Ident, PathBuf, PathBuf),
48    ParserError(Diag<'a>),
49}
50
51pub(crate) fn parse_external_mod(
52    sess: &Session,
53    ident: Ident,
54    span: Span, // The span to blame on errors.
55    module: &ModuleData,
56    mut dir_ownership: DirOwnership,
57    attrs: &mut AttrVec,
58) -> ParsedExternalMod {
59    // We bail on the first error, but that error does not cause a fatal error... (1)
60    let result: Result<_, ModError<'_>> = try {
61        // Extract the file path and the new ownership.
62        let mp = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)?;
63        dir_ownership = mp.dir_ownership;
64
65        // Ensure file paths are acyclic.
66        if let Some(pos) = module.file_path_stack.iter().position(|p| p == &mp.file_path) {
67            do yeet ModError::CircularInclusion(module.file_path_stack[pos..].to_vec());
68        }
69
70        // Actually parse the external file as a module.
71        let mut parser = unwrap_or_emit_fatal(new_parser_from_file(
72            &sess.psess,
73            &mp.file_path,
74            StripTokens::ShebangAndFrontmatter,
75            Some(span),
76        ));
77        let (inner_attrs, items, inner_span) =
78            parser.parse_mod(exp!(Eof)).map_err(|err| ModError::ParserError(err))?;
79        attrs.extend(inner_attrs);
80        (items, inner_span, mp.file_path)
81    };
82
83    // (1) ...instead, we return a dummy module.
84    let ((items, spans, file_path), had_parse_error) = match result {
85        Err(err) => (Default::default(), Err(err.report(sess, span))),
86        Ok(result) => (result, Ok(())),
87    };
88
89    // Extract the directory path for submodules of the module.
90    let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
91
92    ParsedExternalMod { items, spans, file_path, dir_path, dir_ownership, had_parse_error }
93}
94
95pub(crate) fn mod_dir_path(
96    sess: &Session,
97    ident: Ident,
98    attrs: &[Attribute],
99    module: &ModuleData,
100    mut dir_ownership: DirOwnership,
101    inline: Inline,
102) -> (PathBuf, DirOwnership) {
103    match inline {
104        Inline::Yes
105            if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) =>
106        {
107            // For inline modules file path from `#[path]` is actually the directory path
108            // for historical reasons, so we don't pop the last segment here.
109            (file_path, DirOwnership::Owned { relative: None })
110        }
111        Inline::Yes => {
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            let mut dir_path = module.dir_path.clone();
119            if let DirOwnership::Owned { relative } = &mut dir_ownership {
120                if let Some(ident) = relative.take() {
121                    // Remove the relative offset.
122                    dir_path.push(ident.as_str());
123                }
124            }
125            dir_path.push(ident.as_str());
126
127            (dir_path, dir_ownership)
128        }
129        Inline::No { .. } => {
130            // FIXME: This is a subset of `parse_external_mod` without actual parsing,
131            // check whether the logic for unloaded, loaded and inline modules can be unified.
132            let file_path = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)
133                .map(|mp| {
134                    dir_ownership = mp.dir_ownership;
135                    mp.file_path
136                })
137                .unwrap_or_default();
138
139            // Extract the directory path for submodules of the module.
140            let dir_path = file_path.parent().unwrap_or(&file_path).to_owned();
141
142            (dir_path, dir_ownership)
143        }
144    }
145}
146
147fn mod_file_path<'a>(
148    sess: &'a Session,
149    ident: Ident,
150    attrs: &[Attribute],
151    dir_path: &Path,
152    dir_ownership: DirOwnership,
153) -> Result<ModulePathSuccess, ModError<'a>> {
154    if let Some(file_path) = mod_file_path_from_attr(sess, attrs, dir_path) {
155        // All `#[path]` files are treated as though they are a `mod.rs` file.
156        // This means that `mod foo;` declarations inside `#[path]`-included
157        // files are siblings,
158        //
159        // Note that this will produce weirdness when a file named `foo.rs` is
160        // `#[path]` included and contains a `mod foo;` declaration.
161        // If you encounter this, it's your own darn fault :P
162        let dir_ownership = DirOwnership::Owned { relative: None };
163        return Ok(ModulePathSuccess { file_path, dir_ownership });
164    }
165
166    let relative = match dir_ownership {
167        DirOwnership::Owned { relative } => relative,
168        DirOwnership::UnownedViaBlock => None,
169    };
170    let result = default_submod_path(&sess.psess, ident, relative, dir_path);
171    match dir_ownership {
172        DirOwnership::Owned { .. } => result,
173        DirOwnership::UnownedViaBlock => Err(ModError::ModInBlock(match result {
174            Ok(_) | Err(ModError::MultipleCandidates(..)) => Some(ident),
175            _ => None,
176        })),
177    }
178}
179
180/// Derive a submodule path from the first found `#[path = "path_string"]`.
181/// The provided `dir_path` is joined with the `path_string`.
182pub(crate) fn mod_file_path_from_attr(
183    sess: &Session,
184    attrs: &[Attribute],
185    dir_path: &Path,
186) -> Option<PathBuf> {
187    // Extract path string from first `#[path = "path_string"]` attribute.
188    let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
189    let Some(path_sym) = first_path.value_str() else {
190        // This check is here mainly to catch attempting to use a macro,
191        // such as `#[path = concat!(...)]`. This isn't supported because
192        // otherwise the `InvocationCollector` would need to defer loading
193        // a module until the `#[path]` attribute was expanded, and it
194        // doesn't support that (and would likely add a bit of complexity).
195        // Usually bad forms are checked during semantic analysis via
196        // `TyCtxt::check_mod_attrs`), but by the time that runs the macro
197        // is expanded, and it doesn't give an error.
198        validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, first_path, sym::path);
199    };
200
201    let path_str = path_sym.as_str();
202
203    // On windows, the base path might have the form
204    // `\\?\foo\bar` in which case it does not tolerate
205    // mixed `/` and `\` separators, so canonicalize
206    // `/` to `\`.
207    #[cfg(windows)]
208    let path_str = path_str.replace("/", "\\");
209
210    Some(dir_path.join(path_str))
211}
212
213/// Returns a path to a module.
214// Public for rustfmt usage.
215pub fn default_submod_path<'a>(
216    psess: &'a ParseSess,
217    ident: Ident,
218    relative: Option<Ident>,
219    dir_path: &Path,
220) -> Result<ModulePathSuccess, ModError<'a>> {
221    // If we're in a foo.rs file instead of a mod.rs file,
222    // we need to look for submodules in
223    // `./foo/<ident>.rs` and `./foo/<ident>/mod.rs` rather than
224    // `./<ident>.rs` and `./<ident>/mod.rs`.
225    let relative_prefix_string;
226    let relative_prefix = if let Some(ident) = relative {
227        relative_prefix_string = format!("{}{}", ident.name, path::MAIN_SEPARATOR);
228        &relative_prefix_string
229    } else {
230        ""
231    };
232
233    let default_path_str = format!("{}{}.rs", relative_prefix, ident.name);
234    let secondary_path_str =
235        format!("{}{}{}mod.rs", relative_prefix, ident.name, path::MAIN_SEPARATOR);
236    let default_path = dir_path.join(&default_path_str);
237    let secondary_path = dir_path.join(&secondary_path_str);
238    let default_exists = psess.source_map().file_exists(&default_path);
239    let secondary_exists = psess.source_map().file_exists(&secondary_path);
240
241    match (default_exists, secondary_exists) {
242        (true, false) => Ok(ModulePathSuccess {
243            file_path: default_path,
244            dir_ownership: DirOwnership::Owned { relative: Some(ident) },
245        }),
246        (false, true) => Ok(ModulePathSuccess {
247            file_path: secondary_path,
248            dir_ownership: DirOwnership::Owned { relative: None },
249        }),
250        (false, false) => Err(ModError::FileNotFound(ident, default_path, secondary_path)),
251        (true, true) => Err(ModError::MultipleCandidates(ident, default_path, secondary_path)),
252    }
253}
254
255impl ModError<'_> {
256    fn report(self, sess: &Session, span: Span) -> ErrorGuaranteed {
257        match self {
258            ModError::CircularInclusion(file_paths) => {
259                let path_to_string = |path: &PathBuf| path.display().to_string();
260
261                let paths = file_paths
262                    .iter()
263                    .map(path_to_string)
264                    .chain(once(path_to_string(&file_paths[0])))
265                    .collect::<Vec<_>>();
266
267                let modules = paths.join(" -> ");
268
269                sess.dcx().emit_err(ModuleCircular { span, modules })
270            }
271            ModError::ModInBlock(ident) => sess.dcx().emit_err(ModuleInBlock {
272                span,
273                name: ident.map(|name| ModuleInBlockName { span, name }),
274            }),
275            ModError::FileNotFound(name, default_path, secondary_path) => {
276                sess.dcx().emit_err(ModuleFileNotFound {
277                    span,
278                    name,
279                    default_path: default_path.display().to_string(),
280                    secondary_path: secondary_path.display().to_string(),
281                })
282            }
283            ModError::MultipleCandidates(name, default_path, secondary_path) => {
284                sess.dcx().emit_err(ModuleMultipleCandidates {
285                    span,
286                    name,
287                    default_path: default_path.display().to_string(),
288                    secondary_path: secondary_path.display().to_string(),
289                })
290            }
291            ModError::ParserError(err) => err.emit(),
292        }
293    }
294}