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 relative: Option<Ident>,
25 },
26 UnownedViaBlock,
27}
28
29pub 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, module: &ModuleData,
57 mut dir_ownership: DirOwnership,
58 attrs: &mut AttrVec,
59) -> ParsedExternalMod {
60 let result: Result<_, ModError<'_>> = try {
62 let mp = mod_file_path(sess, ident, attrs, &module.dir_path, dir_ownership)?;
64 dir_ownership = mp.dir_ownership;
65
66 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 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 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 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 (file_path, DirOwnership::Owned { relative: None })
111 }
112 Inline::Yes => {
113 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 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 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 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 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
181pub(crate) fn mod_file_path_from_attr(
184 sess: &Session,
185 attrs: &[Attribute],
186 dir_path: &Path,
187) -> Option<PathBuf> {
188 let first_path = attrs.iter().find(|at| at.has_name(sym::path))?;
191 let Some(path_sym) = first_path.value_str() else {
192 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 #[cfg(windows)]
220 let path_str = path_str.replace("/", "\\");
221
222 Some(dir_path.join(path_str))
223}
224
225pub 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 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}