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