forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreferences.rs
More file actions
532 lines (473 loc) · 19.3 KB
/
Copy pathreferences.rs
File metadata and controls
532 lines (473 loc) · 19.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use async_lsp::ResponseError;
use common::InputDb;
use hir::{
core::semantic::reference::Target, hir_def::TopLevelMod, lower::map_file_to_mod, span::LazySpan,
};
use crate::{
backend::Backend,
util::{to_lsp_location_from_lazy_span, to_lsp_location_from_scope, to_offset_from_position},
};
use super::goto::Cursor;
/// Find all references to the symbol at the cursor position.
fn find_references_at_cursor<'db>(
db: &'db impl hir::SpannedHirDb,
top_mod: TopLevelMod<'db>,
cursor: Cursor,
) -> Vec<async_lsp::lsp_types::Location> {
// Use the simplified API to get the target at cursor
let resolution = top_mod.target_at(db, cursor);
let Some(target) = resolution.first() else {
return vec![];
};
let mut locations = vec![];
match &target {
Target::Scope(target_scope) => {
// Search all modules in the ingot
let ingot = top_mod.ingot(db);
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 matched.span.resolve(db).is_some()
&& let Ok(location) = to_lsp_location_from_lazy_span(db, matched.span)
{
locations.push(location);
}
}
}
// Include the definition location first
if let Ok(def_location) = to_lsp_location_from_scope(db, *target_scope) {
locations.insert(0, def_location);
}
}
Target::Local { span, .. } => {
// For locals, search within the function body
for matched in top_mod.references_to_target(db, target) {
if matched.span.resolve(db).is_some()
&& let Ok(location) = to_lsp_location_from_lazy_span(db, matched.span)
{
locations.push(location);
}
}
// Include the definition location first
if let Ok(def_location) = to_lsp_location_from_lazy_span(db, span.clone()) {
locations.insert(0, def_location);
}
}
}
locations
}
pub async fn handle_references(
backend: &Backend,
params: async_lsp::lsp_types::ReferenceParams,
) -> Result<Option<Vec<async_lsp::lsp_types::Location>>, ResponseError> {
let internal_url =
backend.map_client_uri_to_internal(params.text_document_position.text_document.uri.clone());
// Quick existence check on actor thread
if backend
.db
.workspace()
.get(&backend.db, &internal_url)
.is_none()
{
return Ok(None);
}
let position = params.text_document_position.position;
// Spawn heavy reference resolution on the worker pool with a db snapshot
let locations: Vec<async_lsp::lsp_types::Location> = backend
.spawn_on_workers(move |db| {
let Some(file) = db.workspace().get(db, &internal_url) else {
return vec![];
};
let file_text = file.text(db);
let cursor: Cursor = to_offset_from_position(position, file_text.as_str());
let top_mod = map_file_to_mod(db, file);
find_references_at_cursor(db, top_mod, cursor)
})
.await
.map_err(|e| {
tracing::error!("references worker failed: {e}");
ResponseError::new(async_lsp::ErrorCode::INTERNAL_ERROR, e.to_string())
})?;
// Map internal URIs to client URIs (lightweight, on actor thread)
let locations: Vec<_> = locations
.into_iter()
.map(|mut location| {
location.uri = backend.map_internal_uri_to_client(location.uri);
location
})
.collect();
if locations.is_empty() {
Ok(None)
} else {
Ok(Some(locations))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::load_ingot_from_directory;
use codespan_reporting::{
diagnostic::{Diagnostic, Label},
files::SimpleFiles,
term::{
self,
termcolor::{BufferWriter, ColorChoice},
},
};
use common::indexmap::IndexMap;
use common::ingot::IngotKind;
use dir_test::{Fixture, dir_test};
use driver::DriverDataBase;
use hir::hir_def::{ItemKind, PathId, scope_graph::ScopeId};
use hir::span::{DynLazySpan, LazySpan};
use hir::visitor::{Visitor, VisitorCtxt, prelude::LazyPathSpan};
use parser::TextSize;
use rustc_hash::FxHashMap;
use std::collections::BTreeMap;
use test_utils::snap_test;
use url::Url;
/// Test infrastructure: collects all paths for cursor testing.
#[derive(Default)]
struct PathSpanCollector<'db> {
paths: Vec<(PathId<'db>, ScopeId<'db>, LazyPathSpan<'db>)>,
}
impl<'db, 'ast: 'db> Visitor<'ast> for PathSpanCollector<'db> {
fn visit_path(
&mut self,
ctxt: &mut VisitorCtxt<'ast, LazyPathSpan<'ast>>,
path: PathId<'db>,
) {
let Some(span) = ctxt.span() else {
return;
};
let scope = ctxt.scope();
self.paths.push((path, scope, span));
}
}
/// Property formatter for annotating references in snapshots.
struct ReferenceFormatter<'db> {
properties: IndexMap<TopLevelMod<'db>, Vec<(String, DynLazySpan<'db>)>>,
top_mod_to_file: FxHashMap<TopLevelMod<'db>, usize>,
code_span_files: SimpleFiles<String, String>,
}
impl<'db> ReferenceFormatter<'db> {
fn new() -> Self {
Self {
properties: Default::default(),
top_mod_to_file: Default::default(),
code_span_files: SimpleFiles::new(),
}
}
fn register_top_mod(&mut self, path: &str, text: &str, top_mod: TopLevelMod<'db>) {
let file_id = self.code_span_files.add(path.to_string(), text.to_string());
self.top_mod_to_file.insert(top_mod, file_id);
}
fn push_prop(&mut self, top_mod: TopLevelMod<'db>, span: DynLazySpan<'db>, prop: String) {
self.properties
.entry(top_mod)
.or_default()
.push((prop, span));
}
fn finish(&mut self, db: &'db dyn hir::SpannedHirDb) -> String {
let writer = BufferWriter::stderr(ColorChoice::Never);
let mut buffer = writer.buffer();
let config = term::Config::default();
for top_mod in self.top_mod_to_file.keys() {
if !self.properties.contains_key(top_mod) {
continue;
}
let diags = self.properties[top_mod]
.iter()
.filter_map(|(prop, span)| {
let resolved_span = span.resolve(db)?;
let file_id = self.top_mod_to_file[top_mod];
let diag = Diagnostic::note().with_labels(vec![
Label::primary(file_id, resolved_span.range).with_message(prop),
]);
Some((
(
resolved_span.file,
(resolved_span.range.start(), resolved_span.range.end()),
),
diag,
))
})
.collect::<BTreeMap<_, _>>();
for diag in diags.values() {
term::emit(&mut buffer, &config, &self.code_span_files, diag).unwrap();
}
}
std::str::from_utf8(buffer.as_slice()).unwrap().to_string()
}
}
fn extract_cursor_positions_from_spans(
db: &DriverDataBase,
top_mod: TopLevelMod,
) -> Vec<TextSize> {
let mut visitor_ctxt = VisitorCtxt::with_top_mod(db, top_mod);
let mut path_collector = PathSpanCollector::default();
path_collector.visit_top_mod(&mut visitor_ctxt, top_mod);
let mut cursors = Vec::new();
// Collect cursors from path references
for (path, _, lazy_span) in path_collector.paths {
for idx in 0..=path.segment_index(db) {
if let Some(seg_span) = lazy_span.clone().segment(idx).resolve(db) {
cursors.push(seg_span.range.start());
}
}
}
// Also collect cursors from item definition sites
let scope_graph = top_mod.scope_graph(db);
for item in scope_graph.items_dfs(db) {
if let Some(name_span) = item.name_span()
&& let Some(span) = name_span.resolve(db)
{
cursors.push(span.range.start());
}
// Collect cursors from non-item children (variants, fields, etc.)
for child in scope_graph.children(ScopeId::from_item(item)) {
if child.to_item().is_some() {
continue;
}
if let Some(name_span) = child.name_span(db)
&& let Some(span) = name_span.resolve(db)
{
cursors.push(span.range.start());
}
}
// Also collect cursors from function parameter names and local bindings
if let ItemKind::Func(func) = item {
for (idx, _param) in func.params(db).enumerate() {
let param_span = func.span().params().param(idx);
if let Some(span) = param_span.name().resolve(db) {
cursors.push(span.range.start());
}
}
// Collect cursors from local variable bindings in the body
if let Some(body) = func.body(db) {
use hir::hir_def::{Partial, Pat};
for (pat_id, pat) in body.pats(db).iter() {
// Only collect simple identifier patterns (local bindings)
if let Partial::Present(Pat::Path(Partial::Present(path), _)) = pat
&& path.as_ident(db).is_some()
{
let pat_span = pat_id.span(body).into_path_pat().path();
if let Some(span) = pat_span.resolve(db) {
cursors.push(span.range.start());
}
}
}
}
}
}
cursors.sort();
cursors.dedup();
cursors
}
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/test_files/hoverable",
glob: "**/*.fe",
)]
fn test_references_multiple_files(fixture: Fixture<&str>) {
let cargo_manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let ingot_base_dir = std::path::Path::new(&cargo_manifest_dir).join("test_files/hoverable");
let mut db = DriverDataBase::default();
load_ingot_from_directory(&mut db, &ingot_base_dir);
let fe_source_path = fixture.path();
let file_url = Url::from_file_path(fe_source_path).unwrap();
let ingot = db
.workspace()
.containing_ingot(&db, file_url.clone())
.unwrap();
assert_eq!(ingot.kind(&db), IngotKind::Local);
let mut formatter = ReferenceFormatter::new();
// Register all files in the ingot and collect cursors from all of them
let mut all_cursors: Vec<(TextSize, TopLevelMod<'_>)> = Vec::new();
for (url, file) in ingot.files(&db).iter() {
if !url.path().ends_with(".fe") {
continue;
}
let top_mod = map_file_to_mod(&db, file);
let text = file.text(&db);
// Use just the filename for cleaner snapshots
let path = std::path::Path::new(url.path())
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(url.path());
formatter.register_top_mod(path, text.as_str(), top_mod);
// Collect cursors from this file
let cursors = extract_cursor_positions_from_spans(&db, top_mod);
for cursor in cursors {
all_cursors.push((cursor, top_mod));
}
}
// For each cursor from any file, find all references and annotate them
for (cursor, cursor_top_mod) in &all_cursors {
let locations = find_references_at_cursor(&db, *cursor_top_mod, *cursor);
if locations.is_empty() {
continue;
}
// Group references by target symbol to show def + refs together
let total_refs = locations.len();
// Annotate each location (including definition which is first)
for (idx, loc) in locations.iter().enumerate() {
let ref_url = Url::parse(loc.uri.as_str()).unwrap();
if let Some(ref_file) = db.workspace().get(&db, &ref_url) {
let ref_top_mod = map_file_to_mod(&db, ref_file);
let ref_text = ref_file.text(&db);
let ref_offset = lsp_position_to_offset(&loc.range.start, ref_text.as_str());
// For the definition (first location), annotate with the target's span
// For other locations, use reference_at
if idx == 0 {
// First location is the definition - use target_at to handle both
// item definitions and local/param bindings
if let Some(target) = ref_top_mod.target_at(&db, ref_offset).first() {
let annotation = format!(
"def: defined here @ {}:{} ({} refs)",
loc.range.start.line + 1,
loc.range.start.character,
total_refs
);
match target {
Target::Scope(scope) => {
if let Some(name_span) = scope.name_span(&db) {
formatter.push_prop(ref_top_mod, name_span, annotation);
}
}
Target::Local { span, .. } => {
formatter.push_prop(ref_top_mod, span.clone(), annotation);
}
}
}
} else {
// Regular reference
if let Some(reference) = ref_top_mod.reference_at(&db, ref_offset) {
let annotation = format!(
"ref: {}:{}",
loc.range.start.line + 1,
loc.range.start.character
);
formatter.push_prop(ref_top_mod, reference.span(), annotation);
}
}
}
}
}
let snapshot = formatter.finish(&db);
snap_test!(snapshot, fixture.path());
}
fn lsp_position_to_offset(position: &async_lsp::lsp_types::Position, text: &str) -> TextSize {
let mut line = 0;
let mut col = 0;
for (offset, ch) in text.char_indices() {
if line == position.line && col == position.character {
return TextSize::from(offset as u32);
}
if ch == '\n' {
line += 1;
col = 0;
} else {
col += 1;
}
}
TextSize::from(text.len() as u32)
}
#[test]
fn test_msg_variant_resolution() {
let mut db = DriverDataBase::default();
let code = r#"msg TokenMsg {
#[selector = 0x01]
Mint { to: i32, amount: i32 } -> bool,
#[selector = 0x02]
Burn { amount: i32 } -> bool,
}
pub contract Token {
supply: i32
recv TokenMsg {
Mint { to, amount } -> bool uses (mut supply) {
supply += amount
true
}
Burn { amount } -> bool uses (mut supply) {
supply -= amount
true
}
}
}
"#;
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);
// Helper to get cursor position from line:col (0-indexed)
let text = file.text(&db);
let offset_at = |line: u32, col: u32| -> TextSize {
let mut cur_line = 0u32;
let mut cur_col = 0u32;
for (i, ch) in text.char_indices() {
if cur_line == line && cur_col == col {
return TextSize::from(i as u32);
}
if ch == '\n' {
cur_line += 1;
cur_col = 0;
} else {
cur_col += 1;
}
}
TextSize::from(text.len() as u32)
};
// 1. Cursor on "Mint" in msg block definition → should resolve to the struct
let mint_def_cursor = offset_at(2, 2);
let mint_def_target = top_mod.target_at(&db, mint_def_cursor);
assert!(
matches!(mint_def_target.first(), Some(Target::Scope(_))),
"target_at on Mint in msg block should resolve to a scope, not local"
);
// 2. definition_at should find the Mint struct definition
let mint_def = top_mod.definition_at(&db, mint_def_cursor);
assert!(
mint_def.is_some(),
"definition_at should find Mint in msg block"
);
// 3. Cursor on "Mint" in recv arm → should resolve to the same struct
let mint_recv_cursor = offset_at(11, 4);
let mint_recv_target = top_mod.target_at(&db, mint_recv_cursor);
assert!(
matches!(mint_recv_target.first(), Some(Target::Scope(_))),
"target_at on Mint in recv arm should resolve to a scope (goto-definition)"
);
// 4. Both should resolve to the same scope (the Mint struct)
if let (Some(Target::Scope(def_scope)), Some(Target::Scope(recv_scope))) =
(mint_def_target.first(), mint_recv_target.first())
{
assert_eq!(
*def_scope, *recv_scope,
"Mint in msg block and recv arm should resolve to the same scope"
);
}
// 5. references_to_target should find the recv arm reference
let target = Target::Scope(mint_def.unwrap());
let refs = top_mod.references_to_target(&db, &target);
let ref_snippets: Vec<String> = refs
.iter()
.filter_map(|m| {
let span = m.span.resolve(&db)?;
let start: usize = span.range.start().into();
let end: usize = span.range.end().into();
Some(text.as_str()[start..end].to_string())
})
.collect();
assert!(
ref_snippets.iter().filter(|s| *s == "Mint").count() >= 2,
"references_to_target for Mint should find at least 2 refs \
(msg block + recv arm), got: {:?}",
ref_snippets
);
}
}