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        relative: Option<Ident>,
24    },
25    UnownedViaBlock,
26}
27
28pub 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, module: &ModuleData,
56    mut dir_ownership: DirOwnership,
57    attrs: &mut AttrVec,
58) -> ParsedExternalMod {
59    let result: Result<_, ModError<'_>> = try {
61        let mp = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)?;
63        dir_ownership = mp.dir_ownership;
64
65        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        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    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    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            (file_path, DirOwnership::Owned { relative: None })
110        }
111        Inline::Yes => {
112            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                    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            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            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        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
180pub(crate) fn mod_file_path_from_attr(
183    sess: &Session,
184    attrs: &[Attribute],
185    dir_path: &Path,
186) -> Option<PathBuf> {
187    let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
189    let Some(path_sym) = first_path.value_str() else {
190        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    #[cfg(windows)]
208    let path_str = path_str.replace("/", "\\");
209
210    Some(dir_path.join(path_str))
211}
212
213pub 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    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}