forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhover.rs
More file actions
298 lines (270 loc) · 9.25 KB
/
Copy pathhover.rs
File metadata and controls
298 lines (270 loc) · 9.25 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
use anyhow::Error;
use async_lsp::lsp_types::Hover;
use common::file::File;
use hir::{
HirDb,
analysis::ty::{
ProviderAddressSpace,
ty_check::{EffectParamSite, LocalBinding, ParamSite},
},
core::semantic::{
EffectEnvView, ProviderSource,
reference::{ReferenceView, Target},
},
hir_def::{FieldParent, ItemKind, PathId, scope_graph::ScopeId},
lower::map_file_to_mod,
span::LazySpan,
};
use tracing::debug;
use super::{
goto::Cursor,
item_info::{get_docstring, get_item_definition_markdown, get_item_path_markdown},
};
use crate::util::{to_lsp_range_from_span, to_offset_from_position};
use driver::DriverDataBase;
/// Returns `(hover_result, doc_path)`.
///
/// `doc_path` is the documentation URL path for the first resolved scope target
/// (e.g. `"mylib::Foo/struct"`), used for `fe/navigate` notifications.
fn local_name_from_reference<'db>(
db: &'db dyn HirDb,
reference: &ReferenceView<'db>,
) -> Option<String> {
let ReferenceView::Path(path_view) = reference else {
return None;
};
let ident = path_view.path.ident(db).to_opt()?;
Some(ident.data(db).to_string())
}
fn contract_from_effect_site<'db>(
db: &'db DriverDataBase,
site: EffectParamSite<'db>,
) -> Option<hir::hir_def::Contract<'db>> {
match site {
EffectParamSite::Contract(contract)
| EffectParamSite::ContractInit { contract }
| EffectParamSite::ContractRecvArm { contract, .. } => Some(contract),
EffectParamSite::Func(func) => match func.scope().parent_item(db) {
Some(ItemKind::Contract(contract)) => Some(contract),
_ => None,
},
}
}
fn effect_key_path_at_site<'db>(
db: &'db DriverDataBase,
site: EffectParamSite<'db>,
idx: usize,
) -> Option<PathId<'db>> {
match site {
EffectParamSite::Func(func) => func.effect_params(db).nth(idx)?.key_path(db),
EffectParamSite::Contract(contract) => contract.effect_params(db).nth(idx)?.key_path(db),
EffectParamSite::ContractInit { contract } => contract
.init(db)?
.effects(db)
.data(db)
.get(idx)?
.key_path
.to_opt(),
EffectParamSite::ContractRecvArm {
contract,
recv_idx,
arm_idx,
} => contract
.recv(db, recv_idx)?
.arm(db, arm_idx)?
.effects(db)
.data(db)
.get(idx)?
.key_path
.to_opt(),
}
}
fn effect_binding_provider_source_at_site<'db>(
db: &'db DriverDataBase,
site: EffectParamSite<'db>,
idx: usize,
) -> Option<ProviderSource<'db>> {
let view = EffectEnvView::new(site);
let provider_idx = view
.resolutions(db)
.into_iter()
.find(|resolution| resolution.requirement_idx as usize == idx)?
.provider_idx;
view.providers(db)
.into_iter()
.find(|provider| provider.provider_idx == provider_idx)
.map(|provider| provider.source)
}
fn contract_field_layout_by_index<'db>(
db: &'db DriverDataBase,
contract: hir::hir_def::Contract<'db>,
field_idx: u32,
) -> Option<(usize, usize, ProviderAddressSpace)> {
let field = contract
.field_layout(db)
.values()
.find(|field| field.index == field_idx)?;
Some((field.slot_offset, field.slot_count, field.address_space))
}
fn contract_field_layout_from_scope<'db>(
db: &'db DriverDataBase,
scope: ScopeId<'db>,
) -> Option<(usize, usize, ProviderAddressSpace)> {
let ScopeId::Field(FieldParent::Contract(contract), idx) = scope else {
return None;
};
if let Some(name) = scope.name(db)
&& let Some(field) = contract.field_layout(db).get(&name)
{
return Some((field.slot_offset, field.slot_count, field.address_space));
}
contract_field_layout_by_index(db, contract, idx as u32)
}
fn contract_field_layout_from_local_binding<'db>(
db: &'db DriverDataBase,
binding: LocalBinding<'db>,
) -> Option<(usize, usize, ProviderAddressSpace)> {
match binding {
LocalBinding::Param {
site: ParamSite::EffectField(effect_site),
idx,
..
} => {
let contract = contract_from_effect_site(db, effect_site)?;
let key_path = effect_key_path_at_site(db, effect_site, idx)?;
let name = key_path.ident(db).to_opt()?;
let field = contract.field_layout(db).get(&name)?;
Some((field.slot_offset, field.slot_count, field.address_space))
}
LocalBinding::EffectParam { site, idx, .. } => {
let ProviderSource::ContractField { field_idx, .. } =
effect_binding_provider_source_at_site(db, site, idx)?
else {
return None;
};
let contract = contract_from_effect_site(db, site)?;
contract_field_layout_by_index(db, contract, field_idx)
}
_ => None,
}
}
fn contract_field_layout_footer<'db>(
db: &'db DriverDataBase,
target: &Target<'db>,
) -> Option<String> {
let (slot_offset, slot_count, address_space) = match target {
Target::Scope(scope) => contract_field_layout_from_scope(db, *scope)?,
Target::Local { binding, .. } => contract_field_layout_from_local_binding(db, *binding)?,
};
Some(format!(
"slot: {slot_offset} (count: {slot_count})\nspace: {}",
address_space.pretty()
))
}
fn hover_markdown_for_target<'db>(
db: &'db DriverDataBase,
reference: &ReferenceView<'db>,
target: &Target<'db>,
) -> Option<String> {
let mut body = match target {
Target::Scope(scope) => {
let item = scope.item();
let pretty_path = get_item_path_markdown(db, item);
let definition_source = get_item_definition_markdown(db, item);
let docs = get_docstring(db, *scope);
[pretty_path, definition_source, docs]
.iter()
.filter_map(|info| info.clone().map(|info| format!("{info}\n")))
.collect::<Vec<String>>()
.join("\n")
}
Target::Local { ty, .. } => {
let name = local_name_from_reference(db, reference)?;
let ty_str = ty.pretty_print(db);
format!("```fe\nlet {name}: {ty_str}\n```")
}
};
if let Some(layout_footer) = contract_field_layout_footer(db, target) {
body.push('\n');
body.push_str(&layout_footer);
body.push('\n');
}
Some(body)
}
pub fn hover_helper(
db: &DriverDataBase,
file: File,
params: async_lsp::lsp_types::HoverParams,
) -> Result<(Option<Hover>, Option<String>), Error> {
debug!("handling hover");
let file_text = file.text(db);
let cursor: Cursor = to_offset_from_position(
params.text_document_position_params.position,
file_text.as_str(),
);
let top_mod = map_file_to_mod(db, file);
// Get the reference at cursor and resolve it
let Some(r) = top_mod.reference_at(db, cursor) else {
return Ok((None, None));
};
let resolution = r.target_at(db, cursor);
// Extract doc path from the first scope target (for fe/navigate)
let doc_path = resolution
.as_slice()
.iter()
.find_map(|target| match target {
Target::Scope(scope) => hir::semantic::scope_to_doc_path(db, *scope),
Target::Local { .. } => None,
});
// Compute the hover range from the reference span at the cursor position.
// For paths, use the specific segment span containing the cursor.
let hover_range = match &r {
ReferenceView::Path(pv) => {
let mut seg_range = None;
for idx in 0..=pv.path.segment_index(db) {
if let Some(resolved) = pv.span.clone().segment(idx).resolve(db)
&& resolved.range.contains(cursor)
{
seg_range = to_lsp_range_from_span(resolved, db).ok();
break;
}
}
seg_range
}
_ => r
.span()
.resolve(db)
.and_then(|s| to_lsp_range_from_span(s, db).ok()),
};
// Build hover content
let info = if resolution.is_ambiguous() {
let mut sections = vec!["**Multiple definitions**\n\n".to_string()];
for (i, target) in resolution.as_slice().iter().enumerate() {
if let Some(section) = hover_markdown_for_target(db, r, target) {
sections.push(format!("{section}\n\n"));
}
if i < resolution.as_slice().len() - 1 {
sections.push("---\n\n".to_string());
}
}
sections.join("")
} else {
let Some(target) = resolution.first() else {
return Ok((None, doc_path));
};
let Some(info) = hover_markdown_for_target(db, r, target) else {
return Ok((None, doc_path));
};
info
};
let result = async_lsp::lsp_types::Hover {
contents: async_lsp::lsp_types::HoverContents::Markup(
async_lsp::lsp_types::MarkupContent {
kind: async_lsp::lsp_types::MarkupKind::Markdown,
value: info,
},
),
range: hover_range,
};
Ok((Some(result), doc_path))
}