Skip to main content

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