Skip to content

Commit cf2f260

Browse files
authored
feat(lsp-policy): 问题工具窗口的树行、折叠与选中交给 Core (#82)
lsp.problems.query 接受平台保存的折叠分组键和选中行键,返回可见的树行 (分组节点在上,诊断在下;不分组时诊断在顶层)、选中行及其位置,文件 分组多返回 name 和 folder。诊断行键由文件、位置和同一位置上的序号组成, 服务器重新发布诊断后选中仍停在同一条上;被折叠的诊断选中移到所在节点, 消失的诊断在按文件分组时移到所在文件节点。
1 parent 18a370d commit cf2f260

5 files changed

Lines changed: 1537 additions & 100 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -671,7 +671,7 @@ or removing a command fails until the table changes in the same commit.
671671
| `lsp.builtinNavigation` | Return lightweight current-file definition/reference locations |
672672
| `lsp.mergeCompletions` | Choose which candidates survive when several prioritized providers complete at one position |
673673
| `lsp.activationPolicy` | Decide whether a language server may start automatically after failures, using a platform monotonic clock |
674-
| `lsp.problems.query` | Filter, order, and group Problems tool-window diagnostics and count them by severity |
674+
| `lsp.problems.query` | Filter, order, and group Problems tool-window diagnostics, count them by severity, and lay the tree rows out |
675675
| `lsp.references.query` | Group Find Usages locations by file and lay out the References tool window's visible rows, selection, and previous/next usages |
676676
| `lsp.references.lines` | Show the lines of References tool-window usages with highlighted usage ranges, as search results show theirs |
677677
| `lsp.startServer` | Start one Rust-owned process/session and begin initialization |
@@ -2979,8 +2979,24 @@ stable `key`, `indices` into the submitted list, and per-severity `counts`),
29792979
`files` (file summaries in file order regardless of `groupBy`),
29802980
`visibleCounts`, and `totalCounts`. `fileKey` is the platform's native file
29812981
identity; `displayPath` is the workspace-relative path and orders files with
2982-
the Project view's natural file-name order. Severity is the LSP number;
2983-
missing or out-of-range values are unknown (`0`) and rank last. Cases:
2982+
the Project view's natural file-name order; file groups also carry `name`
2983+
(its last segment) and `folder` (the rest, empty at the root). Severity is the
2984+
LSP number; missing or out-of-range values are unknown (`0`) and rank last.
2985+
The request also carries the platform-held tree state: `collapsed` (the keys
2986+
of closed group nodes; unknown keys are ignored) and the `selected` row key.
2987+
The response lays the tree out the way IntelliJ IDEA's Problems window does:
2988+
`rows` are the rows that show from top to bottom, each with `key`, `kind`
2989+
(`group`, `diagnostic`), `depth`, `expanded` (group nodes only), `group`, and
2990+
`shows` (the diagnostic the row previews and opens: itself, or the first under
2991+
a node). Group nodes (`file:<fileKey>`, `severity:<n>`) head their diagnostics
2992+
at depth 1; with `groupBy` `none` there are no nodes and the diagnostics sit at
2993+
depth 0. A diagnostic's key is `diagnostic:<line>:<column>:<ordinal>:<fileKey>`,
2994+
where `ordinal` counts the earlier submitted diagnostics at the same file and
2995+
position, so a selection stays on a diagnostic the server republishes at
2996+
another index. `selected` and `selectedRow` name the selected row: an absent
2997+
or unknown key selects nothing, a diagnostic a closed node hides moves the
2998+
selection to that node, and a diagnostic that is gone moves it to its file's
2999+
node when the list is grouped by file and the file still shows. Cases:
29843000
`rust/fixtures/lsp/problems-query-v1.json`.
29853001

29863002
`lsp.references.query` accepts the Find Usages answer as

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,8 @@ pub enum LspCommand {
645645
MergeCompletions,
646646
/// Decides whether a language server may start automatically (`lsp.activationPolicy`).
647647
ActivationPolicy,
648-
/// Filters, orders, and groups Problems tool-window diagnostics (`lsp.problems.query`).
648+
/// Filters, orders, and groups Problems tool-window diagnostics and lays the tree rows out
649+
/// (`lsp.problems.query`).
649650
ProblemsQuery,
650651
/// Groups Find Usages locations by file and lays out the References tool
651652
/// window's rows (`lsp.references.query`).

‎rust/crates/core/src/tests/lsp_policy.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,10 @@ fn malformed_requests_fail_with_invalid_request() {
144144
"lsp.problems.query",
145145
json!({"diagnostics": [], "groupBy": "type"}),
146146
),
147+
(
148+
"lsp.problems.query",
149+
json!({"diagnostics": [], "collapsed": "file:a"}),
150+
),
147151
(
148152
"lsp.references.query",
149153
json!({"locations": [{"fileKey": "a"}]}),

‎rust/crates/lsp-policy/src/problems.rs‎

Lines changed: 188 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
1-
//! Problems tool-window filtering, ordering, and grouping (`lsp.problems.query`).
1+
//! Problems tool-window filtering, ordering, grouping, and tree rows
2+
//! (`lsp.problems.query`).
23
//!
34
//! Platforms submit the diagnostics they display together with the active
45
//! view options. Core returns indices into the submitted list, so the large
56
//! message payload never crosses the boundary a second time. File paths are
67
//! compared with the IDEA natural file-name order that the Project view uses,
78
//! which keeps `File2` before `File10` on both platforms.
9+
//!
10+
//! The tool window shows the groups the way IntelliJ IDEA's Problems window
11+
//! does: a node per file (or severity) over its diagnostics. Platforms keep
12+
//! which nodes are collapsed and which row is selected, and ask Core again
13+
//! after a change; Core returns the rows that show and moves a selection that
14+
//! a collapsed node hides to that node. A diagnostic's row key names its file,
15+
//! position, and place among the diagnostics at that position rather than its
16+
//! index, so the selection stays on it when the server republishes the list.
817
918
use lithe_core_rules::file_names::FileNameKey;
1019
use lithe_protocol::{CoreError, ErrorCode};
1120
use serde::{Deserialize, Serialize};
1221
use serde_json::Value;
1322
use std::cmp::Ordering;
14-
use std::collections::BTreeMap;
23+
use std::collections::{BTreeMap, BTreeSet};
1524

1625
/// LSP severities in display order; unknown (`0`) ranks after hints.
1726
const SEVERITY_RANKS: [u8; 5] = [1, 2, 3, 4, 0];
@@ -26,6 +35,12 @@ struct Request {
2635
sort_by: SortBy,
2736
#[serde(default)]
2837
filter: Filter,
38+
/// The keys of the group nodes the user closed; unknown keys are ignored.
39+
#[serde(default)]
40+
collapsed: Vec<String>,
41+
/// The key of the selected row; absent or unknown selects nothing.
42+
#[serde(default)]
43+
selected: Option<String>,
2944
}
3045

3146
/// One displayed diagnostic. Only the fields that affect filtering and order
@@ -142,13 +157,48 @@ struct Group {
142157
file_key: Option<String>,
143158
#[serde(skip_serializing_if = "Option::is_none")]
144159
display_path: Option<String>,
160+
/// The last segment of a file group's `displayPath`.
161+
#[serde(skip_serializing_if = "Option::is_none")]
162+
name: Option<String>,
163+
/// A file group's `displayPath` without its last segment; empty at the
164+
/// workspace root.
165+
#[serde(skip_serializing_if = "Option::is_none")]
166+
folder: Option<String>,
145167
#[serde(skip_serializing_if = "Option::is_none")]
146168
severity: Option<u8>,
147169
/// Indices into the submitted `diagnostics`, in display order.
148170
indices: Vec<usize>,
149171
counts: SeverityCounts,
150172
}
151173

174+
#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
175+
#[serde(rename_all = "camelCase")]
176+
enum RowKind {
177+
Group,
178+
Diagnostic,
179+
}
180+
181+
#[derive(Serialize)]
182+
#[serde(rename_all = "camelCase")]
183+
struct Row {
184+
/// The group's key, or `diagnostic:<line>:<column>:<ordinal>:<fileKey>`
185+
/// where `ordinal` counts the earlier submitted diagnostics at the same
186+
/// file and position; stable while nodes open and close.
187+
key: String,
188+
kind: RowKind,
189+
/// 0 for a group node and for a diagnostic of the ungrouped list, 1 for a
190+
/// diagnostic under a node.
191+
depth: u8,
192+
/// Whether a node's diagnostics show; absent on a diagnostic.
193+
#[serde(skip_serializing_if = "Option::is_none")]
194+
expanded: Option<bool>,
195+
/// The row's group.
196+
group: usize,
197+
/// The diagnostic the row previews and opens: itself, or the first
198+
/// diagnostic under a node.
199+
shows: usize,
200+
}
201+
152202
#[derive(Serialize)]
153203
#[serde(rename_all = "camelCase")]
154204
struct FileSummary {
@@ -167,6 +217,15 @@ struct Response {
167217
files: Vec<FileSummary>,
168218
visible_counts: SeverityCounts,
169219
total_counts: SeverityCounts,
220+
/// The rows that show, top to bottom; empty when nothing is visible.
221+
rows: Vec<Row>,
222+
/// The key of the selected row, always one of `rows`; absent when nothing
223+
/// is selected.
224+
#[serde(skip_serializing_if = "Option::is_none")]
225+
selected: Option<String>,
226+
/// The position of the selected row in `rows`.
227+
#[serde(skip_serializing_if = "Option::is_none")]
228+
selected_row: Option<usize>,
170229
}
171230

172231
struct Entry<'a> {
@@ -273,14 +332,23 @@ fn query(request: &Request) -> Response {
273332
let groups = match request.group_by {
274333
GroupBy::File => files
275334
.iter()
276-
.map(|file| Group {
277-
key: format!("file:{}", file.facts.file_key),
278-
kind: "file",
279-
file_key: Some(file.facts.file_key.clone()),
280-
display_path: Some(file.facts.display_path.clone()),
281-
severity: None,
282-
indices: file.indices.clone(),
283-
counts: file.counts,
335+
.map(|file| {
336+
let path = file.facts.display_path.as_str();
337+
let (folder, name) = match path.rfind('/') {
338+
Some(at) => (&path[..at], &path[at + 1..]),
339+
None => ("", path),
340+
};
341+
Group {
342+
key: file_group_key(&file.facts.file_key),
343+
kind: "file",
344+
file_key: Some(file.facts.file_key.clone()),
345+
display_path: Some(path.to_string()),
346+
name: Some(name.to_string()),
347+
folder: Some(folder.to_string()),
348+
severity: None,
349+
indices: file.indices.clone(),
350+
counts: file.counts,
351+
}
284352
})
285353
.collect(),
286354
GroupBy::Severity => SEVERITY_RANKS
@@ -299,6 +367,8 @@ fn query(request: &Request) -> Response {
299367
kind: "severity",
300368
file_key: None,
301369
display_path: None,
370+
name: None,
371+
folder: None,
302372
severity: Some(severity),
303373
indices,
304374
counts,
@@ -312,6 +382,8 @@ fn query(request: &Request) -> Response {
312382
kind: "all",
313383
file_key: None,
314384
display_path: None,
385+
name: None,
386+
folder: None,
315387
severity: None,
316388
indices: visible.iter().map(|entry| entry.index).collect(),
317389
counts: visible_counts,
@@ -327,14 +399,120 @@ fn query(request: &Request) -> Response {
327399
counts: file.counts,
328400
})
329401
.collect();
402+
let keys = diagnostic_keys(&request.diagnostics);
403+
let (rows, selected) = tree(request, &groups, &keys);
404+
let selected_row = selected
405+
.as_ref()
406+
.and_then(|key| rows.iter().position(|row| &row.key == key));
330407
Response {
331408
groups,
332409
files,
333410
visible_counts,
334411
total_counts,
412+
rows,
413+
selected,
414+
selected_row,
335415
}
336416
}
337417

418+
/// The rows that show and the key of the selected one. Group nodes head
419+
/// their diagnostics except in the ungrouped list, whose diagnostics sit at
420+
/// the top level. A selected diagnostic that a closed node hides moves to
421+
/// that node; one that is gone moves to its file's node when the list is
422+
/// grouped by file and the file still shows, and is dropped otherwise.
423+
fn tree(request: &Request, groups: &[Group], keys: &[String]) -> (Vec<Row>, Option<String>) {
424+
let headed = request.group_by != GroupBy::None;
425+
let collapsed: BTreeSet<&str> = request.collapsed.iter().map(String::as_str).collect();
426+
let expanded: Vec<bool> = groups
427+
.iter()
428+
.map(|group| !headed || !collapsed.contains(group.key.as_str()))
429+
.collect();
430+
let mut rows = Vec::new();
431+
for (slot, group) in groups.iter().enumerate() {
432+
if headed {
433+
rows.push(Row {
434+
key: group.key.clone(),
435+
kind: RowKind::Group,
436+
depth: 0,
437+
expanded: Some(expanded[slot]),
438+
group: slot,
439+
shows: group.indices[0],
440+
});
441+
}
442+
if !expanded[slot] {
443+
continue;
444+
}
445+
for index in &group.indices {
446+
rows.push(Row {
447+
key: keys[*index].clone(),
448+
kind: RowKind::Diagnostic,
449+
depth: u8::from(headed),
450+
expanded: None,
451+
group: slot,
452+
shows: *index,
453+
});
454+
}
455+
}
456+
457+
let Some(wanted) = request.selected.as_deref() else {
458+
return (rows, None);
459+
};
460+
if headed && groups.iter().any(|group| group.key == wanted) {
461+
return (rows, Some(wanted.to_string()));
462+
}
463+
if let Some(index) = keys.iter().position(|key| key == wanted) {
464+
if let Some(slot) = groups
465+
.iter()
466+
.position(|group| group.indices.contains(&index))
467+
{
468+
let shown = if expanded[slot] {
469+
wanted.to_string()
470+
} else {
471+
groups[slot].key.clone()
472+
};
473+
return (rows, Some(shown));
474+
}
475+
}
476+
let file = (request.group_by == GroupBy::File)
477+
.then(|| diagnostic_file(wanted))
478+
.flatten()
479+
.map(file_group_key)
480+
.filter(|key| groups.iter().any(|group| &group.key == key));
481+
(rows, file)
482+
}
483+
484+
/// Each submitted diagnostic's row key, in submission order.
485+
fn diagnostic_keys(diagnostics: &[DiagnosticFacts]) -> Vec<String> {
486+
let mut seen = BTreeMap::<(&str, u64, u64), usize>::new();
487+
diagnostics
488+
.iter()
489+
.map(|facts| {
490+
let ordinal = seen
491+
.entry((facts.file_key.as_str(), facts.line, facts.column))
492+
.or_insert(0);
493+
let key = format!(
494+
"diagnostic:{}:{}:{}:{}",
495+
facts.line, facts.column, ordinal, facts.file_key
496+
);
497+
*ordinal += 1;
498+
key
499+
})
500+
.collect()
501+
}
502+
503+
/// The `fileKey` a diagnostic row key names, or `None` for another key.
504+
fn diagnostic_file(key: &str) -> Option<&str> {
505+
let mut parts = key.strip_prefix("diagnostic:")?.splitn(4, ':');
506+
for _ in 0..3 {
507+
parts.next()?.parse::<u64>().ok()?;
508+
}
509+
parts.next()
510+
}
511+
512+
fn file_group_key(file_key: &str) -> String {
513+
format!("file:{file_key}")
514+
}
515+
338516
struct FileGroup<'a> {
339517
/// The first visible diagnostic of the file names the group.
340518
facts: &'a DiagnosticFacts,

0 commit comments

Comments
 (0)