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
//! Inlay hints, the types the checker inferred where the source doesn't say,
//! for editors to show inline (and offer to write in).
use std::collections::HashMap;
use rhue_parser::ast::{Block, Expr, ExprKind, FunctionBody, InterpPart, StmtKind, TableItem};
use rhue_types::Type;
use crate::Span;
/// A type shown after a name or a parameter list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct InlayHint {
/// Where it goes, right after the name or after a function's `)`.
pub offset: u32,
/// What's shown: `: number`.
pub label: String,
/// Whether it's a variable's type or a function's results.
pub kind: HintKind,
/// The annotation to insert at `offset` to make it explicit, when the type
/// can be written as Luau syntax.
pub insert: Option<String>,
}
/// What an [`InlayHint`] describes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HintKind {
/// A local's, loop variable's or parameter's type.
Type,
/// A function's results.
Return,
}
/// Longest label that gets shown, longer ones get cut (the annotation doesn't).
const MAX_LABEL: usize = 60;
pub(crate) fn hints(body: &Block, source: &str, types: &[(Span, Type)]) -> Vec<InlayHint> {
// the last type recorded for a span is the final one (flow locals get
// updated in place, functions get recorded every time they're checked)
let types: HashMap<Span, &Type> = types.iter().map(|(s, t)| (*s, t)).collect();
let mut h = Hints {
source,
types,
out: Vec::new(),
};
h.block(body);
h.out.sort_by_key(|x| x.offset);
h.out.dedup_by_key(|x| x.offset);
h.out
}
struct Hints<'a> {
source: &'a str,
types: HashMap<Span, &'a Type>,
out: Vec<InlayHint>,
}
/// Whether a type says nothing worth showing.
fn uninformative(t: &Type) -> bool {
matches!(t, Type::Any | Type::Error | Type::Unknown)
}
impl Hints<'_> {
fn push(&mut self, offset: u32, shown: String, kind: HintKind) {
// results are a pack, which parses as a function type's results
let as_type = match kind {
HintKind::Type => shown.clone(),
HintKind::Return => format!("() -> {shown}"),
};
let insert = rhue_parser::parse_type(&as_type)
.is_ok()
.then(|| format!(": {shown}"));
let mut label = format!(": {shown}");
if label.chars().count() > MAX_LABEL {
label = label.chars().take(MAX_LABEL - 1).collect::<String>() + "…";
}
self.out.push(InlayHint {
offset,
label,
kind,
insert,
});
}
/// A hint for the name declared at `span`, if its type is known.
fn name(&mut self, span: Span) {
if &self.source[span.start as usize..span.end as usize] == "_" {
return;
}
if let Some(t) = self.types.get(&span).copied()
&& !uninformative(t)
{
self.push(span.end, t.to_string(), HintKind::Type);
}
}
fn block(&mut self, b: &Block) {
for s in &b.stmts {
match &s.kind {
StmtKind::Local {
names,
types,
values,
} => {
for v in values {
self.expr(v);
}
for (i, n) in names.iter().enumerate() {
let obvious = matches!(
values.get(i).map(|v| &v.kind),
Some(
ExprKind::Function(_)
| ExprKind::Number(_)
| ExprKind::String(_)
| ExprKind::Interp(_)
| ExprKind::Bool(_)
| ExprKind::Cast { .. }
)
);
if types[i].is_none() && !obvious {
self.name(n.span);
}
}
}
StmtKind::Assign { targets, values } => {
for e in targets.iter().chain(values) {
self.expr(e);
}
}
StmtKind::CompoundAssign { target, value, .. } => {
self.expr(target);
self.expr(value);
}
StmtKind::Do(b) => self.block(b),
StmtKind::While { cond, body } | StmtKind::Repeat { body, cond } => {
self.expr(cond);
self.block(body);
}
StmtKind::If {
branches,
else_block,
} => {
for (c, b) in branches {
self.expr(c);
self.block(b);
}
if let Some(b) = else_block {
self.block(b);
}
}
StmtKind::NumericFor {
start,
limit,
step,
body,
..
} => {
self.expr(start);
self.expr(limit);
if let Some(e) = step {
self.expr(e);
}
self.block(body);
}
StmtKind::GenericFor {
names,
types,
exprs,
body,
} => {
for e in exprs {
self.expr(e);
}
for (n, t) in names.iter().zip(types) {
if t.is_none() {
self.name(n.span);
}
}
self.block(body);
}
StmtKind::Call(e) => self.expr(e),
StmtKind::Function { func, .. } | StmtKind::LocalFunction { func, .. } => {
self.function(func);
}
StmtKind::Break | StmtKind::Continue | StmtKind::TypeAlias(_) => {}
}
}
if let Some(r) = &b.ret {
for v in &r.values {
self.expr(v);
}
}
}
fn function(&mut self, f: &FunctionBody) {
for (i, (p, t)) in f.params.iter().zip(&f.param_types).enumerate() {
if t.is_none() && !(f.is_method && i == 0) {
self.name(p.span);
}
}
if f.return_type.is_none()
&& let Some(Type::Function(ft)) = self.types.get(&f.span).copied()
&& !(ft.rets.types.is_empty() && ft.rets.variadic.is_none())
&& !(ft.rets.types.is_empty() && ft.rets.variadic.as_ref().is_some_and(uninformative))
&& !ft.rets.types.iter().all(uninformative)
&& let Some(close) = self.params_end(f.span)
{
self.push(close, ft.rets.to_string(), HintKind::Return);
}
self.block(&f.body);
}
/// Right after the `)` closing a function's parameters.
fn params_end(&self, span: Span) -> Option<u32> {
let text = &self.source[span.start as usize..span.end as usize];
let mut depth = 0u32;
for t in rhue_lexer::lex(text).tokens {
match t.token {
rhue_lexer::Token::LParen => depth += 1,
rhue_lexer::Token::RParen => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(span.start + t.span.end);
}
}
_ => {}
}
}
None
}
fn expr(&mut self, e: &Expr) {
match &e.kind {
ExprKind::Function(f) => self.function(f),
ExprKind::Interp(parts) => {
for p in parts {
if let InterpPart::Expr(x) = p {
self.expr(x);
}
}
}
ExprKind::Group(x)
| ExprKind::Unary { operand: x, .. }
| ExprKind::Cast { expr: x, .. } => self.expr(x),
ExprKind::Binary { lhs, rhs, .. } => {
self.expr(lhs);
self.expr(rhs);
}
ExprKind::IfElse {
branches,
else_expr,
} => {
for (c, v) in branches {
self.expr(c);
self.expr(v);
}
self.expr(else_expr);
}
ExprKind::Call { callee, args } => {
self.expr(callee);
for a in args {
self.expr(a);
}
}
ExprKind::MethodCall { object, args, .. } => {
self.expr(object);
for a in args {
self.expr(a);
}
}
ExprKind::Index { object, key } => {
self.expr(object);
self.expr(key);
}
ExprKind::Table(items) => {
for item in items {
match item {
TableItem::Positional(v) => self.expr(v),
TableItem::Keyed { key, value } => {
self.expr(key);
self.expr(value);
}
}
}
}
ExprKind::Nil
| ExprKind::Bool(_)
| ExprKind::Number(_)
| ExprKind::String(_)
| ExprKind::Vararg
| ExprKind::Name(_) => {}
}
}
}