From 86c054168c502e2bf768983201e3b8a7da84838d Mon Sep 17 00:00:00 2001 From: Samuel Moelius Date: Sat, 11 Nov 2023 17:20:16 +0000 Subject: [PATCH] Simplify `overscoped_allow` path handling --- .../restriction/overscoped_allow/src/lib.rs | 35 +++++++------------ 1 file changed, 13 insertions(+), 22 deletions(-) diff --git a/examples/restriction/overscoped_allow/src/lib.rs b/examples/restriction/overscoped_allow/src/lib.rs index 0b2ffacad..63e40b37c 100644 --- a/examples/restriction/overscoped_allow/src/lib.rs +++ b/examples/restriction/overscoped_allow/src/lib.rs @@ -28,7 +28,7 @@ use rustc_span::{sym, BytePos, CharPos, FileLines, FileName, RealFileName, Span, use rustfix::diagnostics::{Diagnostic, DiagnosticSpan}; use serde::Deserialize; use std::{ - cell::RefCell, + borrow::Cow, fs::OpenOptions, path::{Path, PathBuf}, }; @@ -106,7 +106,6 @@ struct OverscopedAllow { metadata: OnceCell, diagnostics: Vec, ancestor_meta_item_span_map: FxHashMap>>>, - canonical_paths_cache: RefCell>, } impl_lint_pass!(OverscopedAllow => [OVERSCOPED_ALLOW]); @@ -161,7 +160,6 @@ impl OverscopedAllow { metadata: OnceCell::new(), diagnostics, ancestor_meta_item_span_map: FxHashMap::default(), - canonical_paths_cache: RefCell::new(FxHashMap::default()), } } @@ -336,26 +334,9 @@ impl OverscopedAllow { return false; }; let metadata = self.metadata(&span_local_path); - let lhs = &span_local_path; - let rhs = Path::new(&diagnostic_span.file_name); - for path in [lhs, rhs] { - if_chain! { - if self.canonical_paths_cache.borrow().get(path).is_none(); - if let Ok(canonical_path) = if path.is_absolute() { - path.canonicalize() - } else { - metadata.workspace_root.as_std_path().join(path).canonicalize() - }; - then { - self.canonical_paths_cache - .borrow_mut() - .insert(path.to_path_buf(), canonical_path); - } - } - } + let lhs = &absolutize(metadata, &span_local_path); + let rhs = &absolutize(metadata, Path::new(&diagnostic_span.file_name)); if_chain! { - if let Some(lhs) = self.canonical_paths_cache.borrow().get(lhs); - if let Some(rhs) = self.canonical_paths_cache.borrow().get(rhs); if lhs == rhs; if let Ok(FileLines { lines, .. }) = cx.sess().source_map().span_to_lines(span); if let Some(first_line) = lines.first(); @@ -376,6 +357,16 @@ impl OverscopedAllow { } } +fn absolutize<'a>(metadata: &Metadata, path: &'a Path) -> Cow<'a, Path> { + if path.is_absolute() { + // smoelius: `path` may not point in the workspace. It could point into `$HOME/.cargo`, for + // example. + Cow::Borrowed(path) + } else { + Cow::Owned(metadata.workspace_root.as_std_path().join(path)) + } +} + fn include_trailing_semicolons(cx: &LateContext<'_>, mut span: Span) -> Span { // smoelius: I have seen `span_to_lines` fail on real code. let Ok(FileLines { file, .. }) = cx.sess().source_map().span_to_lines(span) else {