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