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 relative: Option<Ident>,
22 },
23 UnownedViaBlock,
24}
25
26pub 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, module: &ModuleData,
54 mut dir_ownership: DirOwnership,
55 attrs: &mut AttrVec,
56) -> ParsedExternalMod {
57 let result: Result<_, ModError<'_>> = try {
59 let mp = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)?;
61 dir_ownership = mp.dir_ownership;
62
63 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 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 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 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 (file_path, DirOwnership::Owned { relative: None })
104 }
105 Inline::Yes => {
106 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 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 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 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 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
174pub(crate) fn mod_file_path_from_attr(
177 sess: &Session,
178 attrs: &[Attribute],
179 dir_path: &Path,
180) -> Option<PathBuf> {
181 let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
183 let Some(path_sym) = first_path.value_str() else {
184 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 #[cfg(windows)]
202 let path_str = path_str.replace("/", "\\");
203
204 Some(dir_path.join(path_str))
205}
206
207pub 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 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}