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