rust/compiler/rustc_builtin_macros/src/source_util.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

343 lines
12 KiB
Rust
Raw Normal View History

2020-04-27 23:26:11 +05:30
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::token;
use rustc_ast::tokenstream::TokenStream;
use rustc_ast_pretty::pprust;
2024-03-01 02:49:02 +00:00
use rustc_data_structures::sync::Lrc;
use rustc_expand::base::{
check_zero_tts, get_single_str_from_tts, get_single_str_spanned_from_tts, parse_expr,
resolve_path,
};
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt};
use rustc_expand::base::{MacEager, MacResult, MacroExpanderResult};
use rustc_expand::module::DirOwnership;
use rustc_parse::new_parser_from_file;
use rustc_parse::parser::{ForceCollect, Parser};
2020-01-05 10:47:20 +01:00
use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
2024-03-01 02:49:02 +00:00
use rustc_span::source_map::SourceMap;
2020-01-01 19:30:57 +01:00
use rustc_span::symbol::Symbol;
use rustc_span::{Pos, Span};
2018-08-30 11:42:16 +02:00
use smallvec::SmallVec;
2024-03-01 02:49:02 +00:00
use std::path::{Path, PathBuf};
use std::rc::Rc;
// These macros all relate to the file system; they either return
// the column/row/filename of the expression, or they include
// a given file into the current one.
2014-06-09 13:12:30 -07:00
/// line!(): expands to the current line number
pub fn expand_line(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
check_zero_tts(cx, sp, tts, "line!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 12:14:09 +02:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
ExpandResult::Ready(MacEager::expr(cx.expr_u32(topmost, loc.line as u32)))
}
/* column!(): expands to the current column number */
pub fn expand_column(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
check_zero_tts(cx, sp, tts, "column!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 12:14:09 +02:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
2015-02-21 06:56:46 -05:00
ExpandResult::Ready(MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1)))
}
2014-06-09 13:12:30 -07:00
/// file!(): expands to the current filename */
2018-08-18 12:13:56 +02:00
/// The source_file (`loc.file`) contains a bunch more information we could spit
2014-06-09 13:12:30 -07:00
/// out if we wanted.
pub fn expand_file(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
check_zero_tts(cx, sp, tts, "file!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 12:14:09 +02:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt};
ExpandResult::Ready(MacEager::expr(cx.expr_str(
topmost,
Symbol::intern(
&loc.file.name.for_scope(cx.sess, RemapPathScopeComponents::MACRO).to_string_lossy(),
),
)))
}
pub fn expand_stringify(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
let s = pprust::tts_to_string(&tts);
ExpandResult::Ready(MacEager::expr(cx.expr_str(sp, Symbol::intern(&s))))
}
pub fn expand_mod(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
check_zero_tts(cx, sp, tts, "module_path!");
let mod_path = &cx.current_expansion.module.mod_path;
let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
2016-09-01 06:44:54 +00:00
ExpandResult::Ready(MacEager::expr(cx.expr_str(sp, Symbol::intern(&string))))
}
2014-06-09 13:12:30 -07:00
/// include! : parse the given file as an expr
/// This is generally a bad idea because it's going to behave
/// unhygienically.
pub fn expand_include<'cx>(
cx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'cx> {
let sp = cx.with_def_site_ctxt(sp);
let ExpandResult::Ready(mac) = get_single_str_from_tts(cx, sp, tts, "include!") else {
return ExpandResult::Retry(());
};
let file = match mac {
Ok(file) => file,
Err(guar) => return ExpandResult::Ready(DummyResult::any(sp, guar)),
};
// The file will be added to the code map by the parser
let file = match resolve_path(&cx.sess, file.as_str(), sp) {
Ok(f) => f,
Make `DiagnosticBuilder::emit` consuming. This works for most of its call sites. This is nice, because `emit` very much makes sense as a consuming operation -- indeed, `DiagnosticBuilderState` exists to ensure no diagnostic is emitted twice, but it uses runtime checks. For the small number of call sites where a consuming emit doesn't work, the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will be removed in subsequent commits.) Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes consuming, while `delay_as_bug_without_consuming` is added (which will also be removed in subsequent commits.) All this requires significant changes to `DiagnosticBuilder`'s chaining methods. Currently `DiagnosticBuilder` method chaining uses a non-consuming `&mut self -> &mut Self` style, which allows chaining to be used when the chain ends in `emit()`, like so: ``` struct_err(msg).span(span).emit(); ``` But it doesn't work when producing a `DiagnosticBuilder` value, requiring this: ``` let mut err = self.struct_err(msg); err.span(span); err ``` This style of chaining won't work with consuming `emit` though. For that, we need to use to a `self -> Self` style. That also would allow `DiagnosticBuilder` production to be chained, e.g.: ``` self.struct_err(msg).span(span) ``` However, removing the `&mut self -> &mut Self` style would require that individual modifications of a `DiagnosticBuilder` go from this: ``` err.span(span); ``` to this: ``` err = err.span(span); ``` There are *many* such places. I have a high tolerance for tedious refactorings, but even I gave up after a long time trying to convert them all. Instead, this commit has it both ways: the existing `&mut self -> Self` chaining methods are kept, and new `self -> Self` chaining methods are added, all of which have a `_mv` suffix (short for "move"). Changes to the existing `forward!` macro lets this happen with very little additional boilerplate code. I chose to add the suffix to the new chaining methods rather than the existing ones, because the number of changes required is much smaller that way. This doubled chainging is a bit clumsy, but I think it is worthwhile because it allows a *lot* of good things to subsequently happen. In this commit, there are many `mut` qualifiers removed in places where diagnostics are emitted without being modified. In subsequent commits: - chaining can be used more, making the code more concise; - more use of chaining also permits the removal of redundant diagnostic APIs like `struct_err_with_code`, which can be replaced easily with `struct_err` + `code_mv`; - `emit_without_diagnostic` can be removed, which simplifies a lot of machinery, removing the need for `DiagnosticBuilderState`.
2024-01-03 12:17:35 +11:00
Err(err) => {
let guar = err.emit();
return ExpandResult::Ready(DummyResult::any(sp, guar));
}
};
let p = new_parser_from_file(cx.psess(), &file, Some(sp));
// If in the included file we have e.g., `mod bar;`,
// then the path of `bar.rs` should be relative to the directory of `file`.
// See https://github.com/rust-lang/rust/pull/69838/files#r395217057 for a discussion.
// `MacroExpander::fully_expand_fragment` later restores, so "stack discipline" is maintained.
let dir_path = file.parent().unwrap_or(&file).to_owned();
cx.current_expansion.module = Rc::new(cx.current_expansion.module.with_dir_path(dir_path));
cx.current_expansion.dir_ownership = DirOwnership::Owned { relative: None };
struct ExpandInclude<'a> {
p: Parser<'a>,
node_id: ast::NodeId,
}
impl<'a> MacResult for ExpandInclude<'a> {
fn make_expr(mut self: Box<ExpandInclude<'a>>) -> Option<P<ast::Expr>> {
let expr = parse_expr(&mut self.p).ok()?;
if self.p.token != token::Eof {
self.p.psess.buffer_lint(
INCOMPLETE_INCLUDE,
self.p.token.span,
self.node_id,
"include macro expected single expression in source",
);
}
Some(expr)
}
2018-08-30 11:42:16 +02:00
fn make_items(mut self: Box<ExpandInclude<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
2018-08-30 11:42:16 +02:00
let mut ret = SmallVec::new();
loop {
match self.p.parse_item(ForceCollect::No) {
Make `DiagnosticBuilder::emit` consuming. This works for most of its call sites. This is nice, because `emit` very much makes sense as a consuming operation -- indeed, `DiagnosticBuilderState` exists to ensure no diagnostic is emitted twice, but it uses runtime checks. For the small number of call sites where a consuming emit doesn't work, the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will be removed in subsequent commits.) Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes consuming, while `delay_as_bug_without_consuming` is added (which will also be removed in subsequent commits.) All this requires significant changes to `DiagnosticBuilder`'s chaining methods. Currently `DiagnosticBuilder` method chaining uses a non-consuming `&mut self -> &mut Self` style, which allows chaining to be used when the chain ends in `emit()`, like so: ``` struct_err(msg).span(span).emit(); ``` But it doesn't work when producing a `DiagnosticBuilder` value, requiring this: ``` let mut err = self.struct_err(msg); err.span(span); err ``` This style of chaining won't work with consuming `emit` though. For that, we need to use to a `self -> Self` style. That also would allow `DiagnosticBuilder` production to be chained, e.g.: ``` self.struct_err(msg).span(span) ``` However, removing the `&mut self -> &mut Self` style would require that individual modifications of a `DiagnosticBuilder` go from this: ``` err.span(span); ``` to this: ``` err = err.span(span); ``` There are *many* such places. I have a high tolerance for tedious refactorings, but even I gave up after a long time trying to convert them all. Instead, this commit has it both ways: the existing `&mut self -> Self` chaining methods are kept, and new `self -> Self` chaining methods are added, all of which have a `_mv` suffix (short for "move"). Changes to the existing `forward!` macro lets this happen with very little additional boilerplate code. I chose to add the suffix to the new chaining methods rather than the existing ones, because the number of changes required is much smaller that way. This doubled chainging is a bit clumsy, but I think it is worthwhile because it allows a *lot* of good things to subsequently happen. In this commit, there are many `mut` qualifiers removed in places where diagnostics are emitted without being modified. In subsequent commits: - chaining can be used more, making the code more concise; - more use of chaining also permits the removal of redundant diagnostic APIs like `struct_err_with_code`, which can be replaced easily with `struct_err` + `code_mv`; - `emit_without_diagnostic` can be removed, which simplifies a lot of machinery, removing the need for `DiagnosticBuilderState`.
2024-01-03 12:17:35 +11:00
Err(err) => {
err.emit();
break;
}
Ok(Some(item)) => ret.push(item),
Ok(None) => {
if self.p.token != token::Eof {
let token = pprust::token_to_string(&self.p.token);
let msg = format!("expected item, found `{token}`");
self.p.dcx().span_err(self.p.token.span, msg);
}
break;
2019-12-07 03:07:35 +01:00
}
}
}
Some(ret)
}
}
ExpandResult::Ready(Box::new(ExpandInclude { p, node_id: cx.current_expansion.lint_node_id }))
}
/// `include_str!`: read the given file, insert it as a literal string expr
pub fn expand_include_str(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
2024-03-01 02:49:02 +00:00
let ExpandResult::Ready(mac) = get_single_str_spanned_from_tts(cx, sp, tts, "include_str!")
else {
return ExpandResult::Retry(());
};
2024-03-01 02:49:02 +00:00
let (path, path_span) = match mac {
Ok(res) => res,
Err(guar) => return ExpandResult::Ready(DummyResult::any(sp, guar)),
};
2024-03-01 02:49:02 +00:00
ExpandResult::Ready(match load_binary_file(cx, path.as_str().as_ref(), sp, path_span) {
Ok(bytes) => match std::str::from_utf8(&bytes) {
Ok(src) => {
let interned_src = Symbol::intern(src);
MacEager::expr(cx.expr_str(sp, interned_src))
}
Err(_) => {
2024-03-01 02:49:02 +00:00
let guar = cx.dcx().span_err(sp, format!("`{path}` wasn't a utf-8 file"));
DummyResult::any(sp, guar)
}
},
2024-03-01 02:49:02 +00:00
Err(dummy) => dummy,
})
}
pub fn expand_include_bytes(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'static> {
let sp = cx.with_def_site_ctxt(sp);
2024-03-01 02:49:02 +00:00
let ExpandResult::Ready(mac) = get_single_str_spanned_from_tts(cx, sp, tts, "include_bytes!")
else {
return ExpandResult::Retry(());
};
2024-03-01 02:49:02 +00:00
let (path, path_span) = match mac {
Ok(res) => res,
Err(guar) => return ExpandResult::Ready(DummyResult::any(sp, guar)),
};
2024-03-01 02:49:02 +00:00
ExpandResult::Ready(match load_binary_file(cx, path.as_str().as_ref(), sp, path_span) {
Ok(bytes) => {
let expr = cx.expr(sp, ast::ExprKind::IncludedBytes(bytes));
MacEager::expr(expr)
}
Err(dummy) => dummy,
})
}
fn load_binary_file(
compiler: fix few needless_pass_by_ref_mut clippy lints warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\asm.rs:306:28 | 306 | fn err_duplicate_option(p: &mut Parser<'_>, symbol: Symbol, span: Span) { | ^^^^^^^^^^^^^^^ help: consider changing to: `&Parser<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\asm.rs:318:8 | 318 | p: &mut Parser<'a>, | ^^^^^^^^^^^^^^^ help: consider changing to: `&Parser<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\assert.rs:114:25 | 114 | fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PResult<'a, Assert> { | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\asm.rs:32:10 | 32 | ecx: &mut ExtCtxt<'a>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\test.rs:99:9 | 99 | cx: &mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\source_util.rs:237:9 | 237 | cx: &mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\format.rs:809:10 | 809 | ecx: &mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\format.rs:737:10 | 737 | ecx: &mut ExtCtxt<'a>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\format.rs:68:24 | 68 | fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a, MacroInput> { | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\format.rs:607:10 | 607 | ecx: &mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\edition_panic.rs:43:9 | 43 | cx: &'cx mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\concat_bytes.rs:11:9 | 11 | cx: &mut ExtCtxt<'_>, | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\cfg.rs:38:22 | 38 | fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<'a, ast::MetaItem> { | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'a>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut warning: this argument is a mutable reference, but not used mutably --> compiler\rustc_builtin_macros\src\cfg_accessible.rs:13:28 | 13 | fn validate_input<'a>(ecx: &mut ExtCtxt<'_>, mi: &'a ast::MetaItem) -> Option<&'a ast::Path> { | ^^^^^^^^^^^^^^^^ help: consider changing to: `&ExtCtxt<'_>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 12:04:00 +03:00
cx: &ExtCtxt<'_>,
2024-03-01 02:49:02 +00:00
original_path: &Path,
macro_span: Span,
path_span: Span,
) -> Result<Lrc<[u8]>, Box<dyn MacResult>> {
let resolved_path = match resolve_path(&cx.sess, original_path, macro_span) {
Ok(path) => path,
Make `DiagnosticBuilder::emit` consuming. This works for most of its call sites. This is nice, because `emit` very much makes sense as a consuming operation -- indeed, `DiagnosticBuilderState` exists to ensure no diagnostic is emitted twice, but it uses runtime checks. For the small number of call sites where a consuming emit doesn't work, the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will be removed in subsequent commits.) Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes consuming, while `delay_as_bug_without_consuming` is added (which will also be removed in subsequent commits.) All this requires significant changes to `DiagnosticBuilder`'s chaining methods. Currently `DiagnosticBuilder` method chaining uses a non-consuming `&mut self -> &mut Self` style, which allows chaining to be used when the chain ends in `emit()`, like so: ``` struct_err(msg).span(span).emit(); ``` But it doesn't work when producing a `DiagnosticBuilder` value, requiring this: ``` let mut err = self.struct_err(msg); err.span(span); err ``` This style of chaining won't work with consuming `emit` though. For that, we need to use to a `self -> Self` style. That also would allow `DiagnosticBuilder` production to be chained, e.g.: ``` self.struct_err(msg).span(span) ``` However, removing the `&mut self -> &mut Self` style would require that individual modifications of a `DiagnosticBuilder` go from this: ``` err.span(span); ``` to this: ``` err = err.span(span); ``` There are *many* such places. I have a high tolerance for tedious refactorings, but even I gave up after a long time trying to convert them all. Instead, this commit has it both ways: the existing `&mut self -> Self` chaining methods are kept, and new `self -> Self` chaining methods are added, all of which have a `_mv` suffix (short for "move"). Changes to the existing `forward!` macro lets this happen with very little additional boilerplate code. I chose to add the suffix to the new chaining methods rather than the existing ones, because the number of changes required is much smaller that way. This doubled chainging is a bit clumsy, but I think it is worthwhile because it allows a *lot* of good things to subsequently happen. In this commit, there are many `mut` qualifiers removed in places where diagnostics are emitted without being modified. In subsequent commits: - chaining can be used more, making the code more concise; - more use of chaining also permits the removal of redundant diagnostic APIs like `struct_err_with_code`, which can be replaced easily with `struct_err` + `code_mv`; - `emit_without_diagnostic` can be removed, which simplifies a lot of machinery, removing the need for `DiagnosticBuilderState`.
2024-01-03 12:17:35 +11:00
Err(err) => {
let guar = err.emit();
2024-03-01 02:49:02 +00:00
return Err(DummyResult::any(macro_span, guar));
}
};
2024-03-01 02:49:02 +00:00
match cx.source_map().load_binary_file(&resolved_path) {
Ok(data) => Ok(data),
Err(io_err) => {
let mut err = cx.dcx().struct_span_err(
macro_span,
format!("couldn't read `{}`: {io_err}", resolved_path.display()),
);
if original_path.is_relative() {
let source_map = cx.sess.source_map();
let new_path = source_map
.span_to_filename(macro_span.source_callsite())
.into_local_path()
.and_then(|src| find_path_suggestion(source_map, src.parent()?, original_path))
.and_then(|path| path.into_os_string().into_string().ok());
if let Some(new_path) = new_path {
err.span_suggestion(
path_span,
"there is a file with the same name in a different directory",
format!("\"{}\"", new_path.replace('\\', "/").escape_debug()),
rustc_lint_defs::Applicability::MachineApplicable,
);
}
}
let guar = err.emit();
Err(DummyResult::any(macro_span, guar))
2022-10-31 18:30:09 +00:00
}
2024-03-01 02:49:02 +00:00
}
}
fn find_path_suggestion(
source_map: &SourceMap,
base_dir: &Path,
wanted_path: &Path,
) -> Option<PathBuf> {
// Fix paths that assume they're relative to cargo manifest dir
let mut base_c = base_dir.components();
let mut wanted_c = wanted_path.components();
let mut without_base = None;
while let Some(wanted_next) = wanted_c.next() {
if wanted_c.as_path().file_name().is_none() {
break;
}
2024-03-01 02:49:02 +00:00
// base_dir may be absolute
while let Some(base_next) = base_c.next() {
if base_next == wanted_next {
without_base = Some(wanted_c.as_path());
break;
}
}
}
let root_absolute = without_base.into_iter().map(PathBuf::from);
let base_dir_components = base_dir.components().count();
// Avoid going all the way to the root dir
let max_parent_components = if base_dir.is_relative() {
base_dir_components + 1
} else {
base_dir_components.saturating_sub(1)
};
// Try with additional leading ../
let mut prefix = PathBuf::new();
let add = std::iter::from_fn(|| {
prefix.push("..");
Some(prefix.join(wanted_path))
})
2024-03-01 02:49:02 +00:00
.take(max_parent_components.min(3));
// Try without leading directories
let mut trimmed_path = wanted_path;
let remove = std::iter::from_fn(|| {
let mut components = trimmed_path.components();
let removed = components.next()?;
trimmed_path = components.as_path();
let _ = trimmed_path.file_name()?; // ensure there is a file name left
Some([
Some(trimmed_path.to_path_buf()),
(removed != std::path::Component::ParentDir)
.then(|| Path::new("..").join(trimmed_path)),
])
})
.flatten()
.flatten()
.take(4);
for new_path in root_absolute.chain(add).chain(remove) {
if source_map.file_exists(&base_dir.join(&new_path)) {
return Some(new_path);
}
}
None
2012-05-18 10:03:27 -07:00
}