forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_lens.rs
More file actions
402 lines (371 loc) · 13.3 KB
/
Copy pathcode_lens.rs
File metadata and controls
402 lines (371 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
use async_lsp::ResponseError;
use async_lsp::lsp_types::{CodeLens, CodeLensParams, Command};
use common::InputDb;
use hir::{core::semantic::reference::Target, hir_def::ItemKind, lower::map_file_to_mod};
use crate::{
backend::Backend,
util::{to_lsp_location_from_lazy_span, to_lsp_location_from_scope},
};
/// Raw code lens data computed on the worker thread (internal URIs, no JSON).
enum RawCodeLens {
References {
def_location: async_lsp::lsp_types::Location,
ref_locations: Vec<async_lsp::lsp_types::Location>,
},
Implementations {
def_location: async_lsp::lsp_types::Location,
impl_locations: Vec<async_lsp::lsp_types::Location>,
},
}
/// Handle textDocument/codeLens.
pub async fn handle_code_lens(
backend: &Backend,
params: CodeLensParams,
) -> Result<Option<Vec<CodeLens>>, ResponseError> {
let internal_url = backend.map_client_uri_to_internal(params.text_document.uri.clone());
if backend
.db
.workspace()
.get(&backend.db, &internal_url)
.is_none()
{
return Ok(None);
}
// Spawn heavy reference counting on the worker pool
let raw_lenses: Vec<RawCodeLens> = backend
.spawn_on_workers(move |db| compute_code_lens_data(db, &internal_url))
.await
.map_err(|e| {
tracing::error!("code lens worker failed: {e}");
ResponseError::new(async_lsp::ErrorCode::INTERNAL_ERROR, e.to_string())
})?;
// Build CodeLens objects on actor thread (lightweight URI mapping)
let mut lenses = Vec::new();
for raw in raw_lenses {
match raw {
RawCodeLens::References {
mut def_location,
ref_locations,
} => {
def_location.uri = backend.map_internal_uri_to_client(def_location.uri);
let refs: Vec<_> = ref_locations
.into_iter()
.map(|mut loc| {
loc.uri = backend.map_internal_uri_to_client(loc.uri);
loc
})
.collect();
lenses.push(make_references_lens(&def_location, &refs));
}
RawCodeLens::Implementations {
mut def_location,
impl_locations,
} => {
def_location.uri = backend.map_internal_uri_to_client(def_location.uri);
let impls: Vec<_> = impl_locations
.into_iter()
.map(|mut loc| {
loc.uri = backend.map_internal_uri_to_client(loc.uri);
loc
})
.collect();
let count = impls.len();
let title = if count == 1 {
"1 implementation".to_string()
} else {
format!("{count} implementations")
};
lenses.push(CodeLens {
range: def_location.range,
command: Some(Command {
title,
command: "fe.showReferences".to_string(),
arguments: Some(vec![
serde_json::json!(def_location.uri),
serde_json::json!(def_location.range.start),
serde_json::json!(impls),
]),
}),
data: None,
});
}
}
}
// Add codegen view lenses (static, no computation needed)
let codegen_range = async_lsp::lsp_types::Range {
start: async_lsp::lsp_types::Position {
line: 0,
character: 0,
},
end: async_lsp::lsp_types::Position {
line: 0,
character: 0,
},
};
let uri_string = params.text_document.uri.to_string();
for (label, cmd) in [("MIR", "fe.viewMir"), ("Sonatina IR", "fe.viewSonatinaIr")] {
lenses.push(CodeLens {
range: codegen_range,
command: Some(Command {
title: label.to_string(),
command: cmd.to_string(),
arguments: Some(vec![serde_json::json!(uri_string)]),
}),
data: None,
});
}
if lenses.is_empty() {
Ok(None)
} else {
Ok(Some(lenses))
}
}
/// Heavy computation: iterate items, count references, collect locations.
/// Runs on the worker thread with a salsa db snapshot.
fn compute_code_lens_data(db: &driver::DriverDataBase, file_url: &url::Url) -> Vec<RawCodeLens> {
let Some(file) = db.workspace().get(db, file_url) else {
return vec![];
};
let top_mod = map_file_to_mod(db, file);
let scope_graph = top_mod.scope_graph(db);
let ingot = top_mod.ingot(db);
let mut lenses = Vec::new();
for item in scope_graph.items_dfs(db) {
match item {
ItemKind::Func(func) => {
let target = Target::Scope(func.scope());
if let Ok(location) = to_lsp_location_from_scope(db, func.scope()) {
let refs = collect_reference_locations(db, ingot, &target);
lenses.push(RawCodeLens::References {
def_location: location,
ref_locations: refs,
});
}
}
ItemKind::Trait(trait_) => {
if let Ok(location) = to_lsp_location_from_scope(db, trait_.scope()) {
let impls = trait_
.all_impl_traits(db)
.iter()
.filter_map(|imp| to_lsp_location_from_scope(db, imp.scope()).ok())
.collect();
lenses.push(RawCodeLens::Implementations {
def_location: location,
impl_locations: impls,
});
}
}
ItemKind::Struct(s) => {
let target = Target::Scope(s.scope());
if let Ok(location) = to_lsp_location_from_scope(db, s.scope()) {
let refs = collect_reference_locations(db, ingot, &target);
lenses.push(RawCodeLens::References {
def_location: location,
ref_locations: refs,
});
}
}
ItemKind::Enum(e) => {
let target = Target::Scope(e.scope());
if let Ok(location) = to_lsp_location_from_scope(db, e.scope()) {
let refs = collect_reference_locations(db, ingot, &target);
lenses.push(RawCodeLens::References {
def_location: location,
ref_locations: refs,
});
}
}
_ => {}
}
}
lenses
}
fn make_references_lens(
location: &async_lsp::lsp_types::Location,
refs: &[async_lsp::lsp_types::Location],
) -> CodeLens {
let count = refs.len();
let title = if count == 1 {
"1 reference".to_string()
} else {
format!("{count} references")
};
CodeLens {
range: location.range,
command: Some(Command {
title,
command: "fe.showReferences".to_string(),
arguments: Some(vec![
serde_json::json!(location.uri),
serde_json::json!(location.range.start),
serde_json::json!(refs),
]),
}),
data: None,
}
}
fn collect_reference_locations<'db>(
db: &'db driver::DriverDataBase,
ingot: common::ingot::Ingot<'db>,
target: &Target<'db>,
) -> Vec<async_lsp::lsp_types::Location> {
let mut locations = Vec::new();
for (url, file) in ingot.files(db).iter() {
if !url.path().ends_with(".fe") {
continue;
}
let mod_ = map_file_to_mod(db, file);
for matched in mod_.references_to_target(db, target) {
if let Ok(loc) = to_lsp_location_from_lazy_span(db, matched.span) {
locations.push(loc);
}
}
}
locations
}
#[cfg(test)]
mod tests {
use super::*;
use driver::DriverDataBase;
use hir::lower::map_file_to_mod;
use url::Url;
fn collect_lens_data<'db>(
db: &'db DriverDataBase,
top_mod: hir::hir_def::TopLevelMod<'db>,
) -> Vec<(String, String, usize)> {
let scope_graph = top_mod.scope_graph(db);
let ingot = top_mod.ingot(db);
let mut results = Vec::new();
for item in scope_graph.items_dfs(db) {
let (name, kind, count) = match item {
ItemKind::Func(func) => {
let target = Target::Scope(func.scope());
let count = collect_reference_locations(db, ingot, &target).len();
let name = func
.name(db)
.to_opt()
.map(|n| n.data(db).to_string())
.unwrap_or_default();
(name, "func".to_string(), count)
}
ItemKind::Trait(trait_) => {
let count = trait_.all_impl_traits(db).len();
let name = trait_
.name(db)
.to_opt()
.map(|n| n.data(db).to_string())
.unwrap_or_default();
(name, "trait".to_string(), count)
}
ItemKind::Struct(s) => {
let target = Target::Scope(s.scope());
let count = collect_reference_locations(db, ingot, &target).len();
let name = s
.name(db)
.to_opt()
.map(|n| n.data(db).to_string())
.unwrap_or_default();
(name, "struct".to_string(), count)
}
ItemKind::Enum(e) => {
let target = Target::Scope(e.scope());
let count = collect_reference_locations(db, ingot, &target).len();
let name = e
.name(db)
.to_opt()
.map(|n| n.data(db).to_string())
.unwrap_or_default();
(name, "enum".to_string(), count)
}
_ => continue,
};
results.push((name, kind, count));
}
results
}
#[test]
fn test_code_lens_references() {
let mut db = DriverDataBase::default();
let code = r#"struct Point {
x: i32
y: i32
}
fn make_point() -> Point {
Point { x: 1, y: 2 }
}
fn use_point() -> i32 {
let p: Point = make_point()
p.x
}
"#;
let file = db.workspace().touch(
&mut db,
Url::parse("file:///test.fe").unwrap(),
Some(code.to_string()),
);
let top_mod = map_file_to_mod(&db, file);
let data = collect_lens_data(&db, top_mod);
// Point struct should have references (used in make_point and use_point)
let point_data = data.iter().find(|(n, _, _)| n == "Point");
assert!(point_data.is_some(), "should find Point in lens data");
let (_, kind, count) = point_data.unwrap();
assert_eq!(kind, "struct");
assert!(
*count >= 2,
"Point should have at least 2 references, got {count}"
);
// make_point should have a reference (called in use_point)
let make_point = data.iter().find(|(n, _, _)| n == "make_point");
assert!(make_point.is_some(), "should find make_point");
let (_, kind, count) = make_point.unwrap();
assert_eq!(kind, "func");
assert!(
*count >= 1,
"make_point should have at least 1 reference, got {count}"
);
}
#[test]
fn test_code_lens_trait_implementations() {
let mut db = DriverDataBase::default();
let code = r#"trait Runnable {
fn run(self) -> i32
}
struct Task {
id: i32
}
impl Runnable for Task {
fn run(self) -> i32 {
self.id
}
}
"#;
let file = db.workspace().touch(
&mut db,
Url::parse("file:///test.fe").unwrap(),
Some(code.to_string()),
);
let top_mod = map_file_to_mod(&db, file);
let data = collect_lens_data(&db, top_mod);
let runnable = data.iter().find(|(n, _, _)| n == "Runnable");
assert!(runnable.is_some(), "should find Runnable");
let (_, kind, count) = runnable.unwrap();
assert_eq!(kind, "trait");
assert_eq!(*count, 1, "Runnable should have 1 implementation");
}
#[test]
fn test_code_lens_no_references() {
let mut db = DriverDataBase::default();
let code = "fn unused() -> i32 {\n 42\n}\n";
let file = db.workspace().touch(
&mut db,
Url::parse("file:///test.fe").unwrap(),
Some(code.to_string()),
);
let top_mod = map_file_to_mod(&db, file);
let data = collect_lens_data(&db, top_mod);
let unused = data.iter().find(|(n, _, _)| n == "unused");
assert!(unused.is_some());
let (_, _, count) = unused.unwrap();
assert_eq!(*count, 0, "unused function should have 0 references");
}
}