Skip to content

Commit 9fcad82

Browse files
committed
Diagnostic Remap Path Prefixes added.
1 parent 60841f4 commit 9fcad82

File tree

5 files changed

+53
-37
lines changed

5 files changed

+53
-37
lines changed

crates/rust-analyzer/src/config.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use ide_db::helpers::{
1717
};
1818
use lsp_types::{ClientCapabilities, MarkupKind};
1919
use project_model::{CargoConfig, ProjectJson, ProjectJsonData, ProjectManifest, RustcSource};
20-
use rustc_hash::FxHashSet;
20+
use rustc_hash::{FxHashMap, FxHashSet};
2121
use serde::{de::DeserializeOwned, Deserialize};
2222
use vfs::AbsPathBuf;
2323

@@ -99,6 +99,9 @@ config_data! {
9999
diagnostics_enableExperimental: bool = "true",
100100
/// List of rust-analyzer diagnostics to disable.
101101
diagnostics_disabled: FxHashSet<String> = "[]",
102+
/// Map of path prefixes to be substituted when parsing diagnostic file paths.
103+
/// This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
104+
diagnostics_remapPathPrefixes: FxHashMap<String, String> = "{}",
102105
/// List of warnings that should be displayed with info severity.
103106
///
104107
/// The warnings will be indicated by a blue squiggly underline in code
@@ -474,6 +477,7 @@ impl Config {
474477
}
475478
pub fn diagnostics_map(&self) -> DiagnosticsMapConfig {
476479
DiagnosticsMapConfig {
480+
remap_path_prefixes: self.data.diagnostics_remapPathPrefixes.clone(),
477481
warnings_as_info: self.data.diagnostics_warningsAsInfo.clone(),
478482
warnings_as_hint: self.data.diagnostics_warningsAsHint.clone(),
479483
}
@@ -835,6 +839,9 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
835839
"items": { "type": "string" },
836840
"uniqueItems": true,
837841
},
842+
"FxHashMap<String, String>" => set! {
843+
"type": "object",
844+
},
838845
"Option<usize>" => set! {
839846
"type": ["null", "integer"],
840847
"minimum": 0,

crates/rust-analyzer/src/diagnostics.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub(crate) type CheckFixes = Arc<FxHashMap<FileId, Vec<Fix>>>;
1212

1313
#[derive(Debug, Default, Clone)]
1414
pub struct DiagnosticsMapConfig {
15+
pub remap_path_prefixes: FxHashMap<String, String>,
1516
pub warnings_as_info: Vec<String>,
1617
pub warnings_as_hint: Vec<String>,
1718
}

crates/rust-analyzer/src/diagnostics/to_proto.rs

Lines changed: 32 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,12 @@ fn is_dummy_macro_file(file_name: &str) -> bool {
4444
}
4545

4646
/// Converts a Rust span to a LSP location
47-
fn location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
48-
let file_name = resolve_path(workspace_root, &span.file_name);
47+
fn location(
48+
config: &DiagnosticsMapConfig,
49+
workspace_root: &Path,
50+
span: &DiagnosticSpan,
51+
) -> lsp_types::Location {
52+
let file_name = resolve_path(config, workspace_root, &span.file_name);
4953
let uri = url_from_abs_path(&file_name);
5054

5155
// FIXME: this doesn't handle UTF16 offsets correctly
@@ -61,54 +65,46 @@ fn location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location
6165
///
6266
/// This takes locations pointing into the standard library, or generally outside the current
6367
/// workspace into account and tries to avoid those, in case macros are involved.
64-
fn primary_location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
68+
fn primary_location(
69+
config: &DiagnosticsMapConfig,
70+
workspace_root: &Path,
71+
span: &DiagnosticSpan,
72+
) -> lsp_types::Location {
6573
let span_stack = std::iter::successors(Some(span), |span| Some(&span.expansion.as_ref()?.span));
6674
for span in span_stack.clone() {
67-
let abs_path = resolve_path(workspace_root, &span.file_name);
75+
let abs_path = resolve_path(config, workspace_root, &span.file_name);
6876
if !is_dummy_macro_file(&span.file_name) && abs_path.starts_with(workspace_root) {
69-
return location(workspace_root, span);
77+
return location(config, workspace_root, span);
7078
}
7179
}
7280

7381
// Fall back to the outermost macro invocation if no suitable span comes up.
7482
let last_span = span_stack.last().unwrap();
75-
location(workspace_root, last_span)
83+
location(config, workspace_root, last_span)
7684
}
7785

7886
/// Converts a secondary Rust span to a LSP related information
7987
///
8088
/// If the span is unlabelled this will return `None`.
8189
fn diagnostic_related_information(
90+
config: &DiagnosticsMapConfig,
8291
workspace_root: &Path,
8392
span: &DiagnosticSpan,
8493
) -> Option<lsp_types::DiagnosticRelatedInformation> {
8594
let message = span.label.clone()?;
86-
let location = location(workspace_root, span);
95+
let location = location(config, workspace_root, span);
8796
Some(lsp_types::DiagnosticRelatedInformation { location, message })
8897
}
8998

90-
/// Resolves paths mimicking VSCode's behavior when `file_name` starts
91-
/// with the root directory component, which does not discard the base
92-
/// path. If this relative path exists, use it, otherwise fall back
93-
/// to the existing Rust behavior of path joining.
94-
fn resolve_path(workspace_root: &Path, file_name: &str) -> PathBuf {
95-
let file_name = Path::new(file_name);
96-
97-
// Test path with VSCode's path join behavior.
98-
let vscode_path = {
99-
let mut result = PathBuf::from(workspace_root);
100-
result.extend(file_name.components().skip_while(|component| match component {
101-
std::path::Component::RootDir => true,
102-
_ => false,
103-
}));
104-
result
105-
};
106-
if vscode_path.exists() {
107-
return vscode_path;
99+
/// Resolves paths applying any matching path prefix remappings, and then
100+
/// joining the path to the workspace root.
101+
fn resolve_path(config: &DiagnosticsMapConfig, workspace_root: &Path, file_name: &str) -> PathBuf {
102+
match config.remap_path_prefixes.iter().find(|(from, _)| file_name.starts_with(*from)) {
103+
Some((from, to)) => {
104+
workspace_root.join(format!("{}{}", to, file_name.strip_prefix(from).unwrap()))
105+
}
106+
None => workspace_root.join(file_name),
108107
}
109-
110-
// Default to Rust's path join behavior.
111-
workspace_root.join(file_name)
112108
}
113109

114110
struct SubDiagnostic {
@@ -122,6 +118,7 @@ enum MappedRustChildDiagnostic {
122118
}
123119

124120
fn map_rust_child_diagnostic(
121+
config: &DiagnosticsMapConfig,
125122
workspace_root: &Path,
126123
rd: &flycheck::Diagnostic,
127124
) -> MappedRustChildDiagnostic {
@@ -135,7 +132,7 @@ fn map_rust_child_diagnostic(
135132
let mut edit_map: HashMap<lsp_types::Url, Vec<lsp_types::TextEdit>> = HashMap::new();
136133
for &span in &spans {
137134
if let Some(suggested_replacement) = &span.suggested_replacement {
138-
let location = location(workspace_root, span);
135+
let location = location(config, workspace_root, span);
139136
let edit = lsp_types::TextEdit::new(location.range, suggested_replacement.clone());
140137
edit_map.entry(location.uri).or_default().push(edit);
141138
}
@@ -144,15 +141,15 @@ fn map_rust_child_diagnostic(
144141
if edit_map.is_empty() {
145142
MappedRustChildDiagnostic::SubDiagnostic(SubDiagnostic {
146143
related: lsp_types::DiagnosticRelatedInformation {
147-
location: location(workspace_root, spans[0]),
144+
location: location(config, workspace_root, spans[0]),
148145
message: rd.message.clone(),
149146
},
150147
suggested_fix: None,
151148
})
152149
} else {
153150
MappedRustChildDiagnostic::SubDiagnostic(SubDiagnostic {
154151
related: lsp_types::DiagnosticRelatedInformation {
155-
location: location(workspace_root, spans[0]),
152+
location: location(config, workspace_root, spans[0]),
156153
message: rd.message.clone(),
157154
},
158155
suggested_fix: Some(lsp_ext::CodeAction {
@@ -217,15 +214,15 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
217214
let mut tags = Vec::new();
218215

219216
for secondary_span in rd.spans.iter().filter(|s| !s.is_primary) {
220-
let related = diagnostic_related_information(workspace_root, secondary_span);
217+
let related = diagnostic_related_information(config, workspace_root, secondary_span);
221218
if let Some(related) = related {
222219
subdiagnostics.push(SubDiagnostic { related, suggested_fix: None });
223220
}
224221
}
225222

226223
let mut message = rd.message.clone();
227224
for child in &rd.children {
228-
let child = map_rust_child_diagnostic(workspace_root, &child);
225+
let child = map_rust_child_diagnostic(config, workspace_root, &child);
229226
match child {
230227
MappedRustChildDiagnostic::SubDiagnostic(sub) => {
231228
subdiagnostics.push(sub);
@@ -269,7 +266,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
269266
primary_spans
270267
.iter()
271268
.flat_map(|primary_span| {
272-
let primary_location = primary_location(workspace_root, &primary_span);
269+
let primary_location = primary_location(config, workspace_root, &primary_span);
273270

274271
let mut message = message.clone();
275272
if needs_primary_span_label {
@@ -299,7 +296,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
299296
// generated that code.
300297
let is_in_macro_call = i != 0;
301298

302-
let secondary_location = location(workspace_root, &span);
299+
let secondary_location = location(config, workspace_root, &span);
303300
if secondary_location == primary_location {
304301
continue;
305302
}

docs/user/generated_config.adoc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,12 @@ have more false positives than usual.
147147
--
148148
List of rust-analyzer diagnostics to disable.
149149
--
150+
[[rust-analyzer.diagnostics.remapPathPrefixes]]rust-analyzer.diagnostics.remapPathPrefixes (default: `{}`)::
151+
+
152+
--
153+
Map of path prefixes to be substituted when parsing diagnostic file paths.
154+
This should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.
155+
--
150156
[[rust-analyzer.diagnostics.warningsAsHint]]rust-analyzer.diagnostics.warningsAsHint (default: `[]`)::
151157
+
152158
--

editors/code/package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,11 @@
565565
},
566566
"uniqueItems": true
567567
},
568+
"rust-analyzer.diagnostics.remapPathPrefixes": {
569+
"markdownDescription": "Map of path prefixes to be substituted when parsing diagnostic file paths.\nThis should be the reverse mapping of what is passed to `rustc` as `--remap-path-prefix`.",
570+
"default": {},
571+
"type": "object"
572+
},
568573
"rust-analyzer.diagnostics.warningsAsHint": {
569574
"markdownDescription": "List of warnings that should be displayed with info severity.\n\nThe warnings will be indicated by a blue squiggly underline in code\nand a blue icon in the `Problems Panel`.",
570575
"default": [],
@@ -1195,4 +1200,4 @@
11951200
]
11961201
}
11971202
}
1198-
}
1203+
}

0 commit comments

Comments
 (0)