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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
|
//! FIXME: write short doc here
use ra_db::SourceDatabase;
use ra_syntax::{
algo::ancestors_at_offset,
ast::{self, ArgListOwner},
match_ast, AstNode, SyntaxNode, TextUnit,
};
use test_utils::tested_by;
use crate::{db::RootDatabase, CallInfo, FilePosition, FunctionSignature};
/// Computes parameter information for the given call expression.
pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<CallInfo> {
let parse = db.parse(position.file_id);
let syntax = parse.tree().syntax().clone();
// Find the calling expression and it's NameRef
let calling_node = FnCallNode::with_node(&syntax, position.offset)?;
let name_ref = calling_node.name_ref()?;
let analyzer = hir::SourceAnalyzer::new(
db,
hir::Source::new(position.file_id.into(), name_ref.syntax()),
None,
);
let (mut call_info, has_self) = match &calling_node {
FnCallNode::CallExpr(expr) => {
//FIXME: don't poke into Ty
let (callable_def, _subst) = analyzer.type_of(db, &expr.expr()?)?.as_callable()?;
match callable_def {
hir::CallableDef::FunctionId(it) => {
let fn_def = it.into();
(CallInfo::with_fn(db, fn_def), fn_def.has_self_param(db))
}
hir::CallableDef::StructId(it) => (CallInfo::with_struct(db, it.into())?, false),
hir::CallableDef::EnumVariantId(it) => {
(CallInfo::with_enum_variant(db, it.into())?, false)
}
}
}
FnCallNode::MethodCallExpr(expr) => {
let function = analyzer.resolve_method_call(&expr)?;
(CallInfo::with_fn(db, function), function.has_self_param(db))
}
FnCallNode::MacroCallExpr(expr) => {
let macro_def = analyzer.resolve_macro_call(db, &expr)?;
(CallInfo::with_macro(db, macro_def)?, false)
}
};
// If we have a calling expression let's find which argument we are on
let num_params = call_info.parameters().len();
if num_params == 1 {
if !has_self {
call_info.active_parameter = Some(0);
}
} else if num_params > 1 {
// Count how many parameters into the call we are.
if let Some(arg_list) = calling_node.arg_list() {
// Number of arguments specified at the call site
let num_args_at_callsite = arg_list.args().count();
let arg_list_range = arg_list.syntax().text_range();
if !arg_list_range.contains_inclusive(position.offset) {
tested_by!(call_info_bad_offset);
return None;
}
let mut param = std::cmp::min(
num_args_at_callsite,
arg_list
.args()
.take_while(|arg| arg.syntax().text_range().end() < position.offset)
.count(),
);
// If we are in a method account for `self`
if has_self {
param += 1;
}
call_info.active_parameter = Some(param);
}
}
Some(call_info)
}
#[derive(Debug)]
enum FnCallNode {
CallExpr(ast::CallExpr),
MethodCallExpr(ast::MethodCallExpr),
MacroCallExpr(ast::MacroCall),
}
impl FnCallNode {
fn with_node(syntax: &SyntaxNode, offset: TextUnit) -> Option<FnCallNode> {
ancestors_at_offset(syntax, offset).find_map(|node| {
match_ast! {
match node {
ast::CallExpr(it) => { Some(FnCallNode::CallExpr(it)) },
ast::MethodCallExpr(it) => { Some(FnCallNode::MethodCallExpr(it)) },
ast::MacroCall(it) => { Some(FnCallNode::MacroCallExpr(it)) },
_ => { None },
}
}
})
}
fn name_ref(&self) -> Option<ast::NameRef> {
match self {
FnCallNode::CallExpr(call_expr) => Some(match call_expr.expr()? {
ast::Expr::PathExpr(path_expr) => path_expr.path()?.segment()?.name_ref()?,
_ => return None,
}),
FnCallNode::MethodCallExpr(call_expr) => {
call_expr.syntax().children().filter_map(ast::NameRef::cast).nth(0)
}
FnCallNode::MacroCallExpr(call_expr) => call_expr.path()?.segment()?.name_ref(),
}
}
fn arg_list(&self) -> Option<ast::ArgList> {
match self {
FnCallNode::CallExpr(expr) => expr.arg_list(),
FnCallNode::MethodCallExpr(expr) => expr.arg_list(),
FnCallNode::MacroCallExpr(_) => None,
}
}
}
impl CallInfo {
fn with_fn(db: &RootDatabase, function: hir::Function) -> Self {
let signature = FunctionSignature::from_hir(db, function);
CallInfo { signature, active_parameter: None }
}
fn with_struct(db: &RootDatabase, st: hir::Struct) -> Option<Self> {
let signature = FunctionSignature::from_struct(db, st)?;
Some(CallInfo { signature, active_parameter: None })
}
fn with_enum_variant(db: &RootDatabase, variant: hir::EnumVariant) -> Option<Self> {
let signature = FunctionSignature::from_enum_variant(db, variant)?;
Some(CallInfo { signature, active_parameter: None })
}
fn with_macro(db: &RootDatabase, macro_def: hir::MacroDef) -> Option<Self> {
let signature = FunctionSignature::from_macro(db, macro_def)?;
Some(CallInfo { signature, active_parameter: None })
}
fn parameters(&self) -> &[String] {
&self.signature.parameters
}
}
#[cfg(test)]
mod tests {
use test_utils::covers;
use crate::mock_analysis::single_file_with_position;
use super::*;
// These are only used when testing
impl CallInfo {
fn doc(&self) -> Option<hir::Documentation> {
self.signature.doc.clone()
}
fn label(&self) -> String {
self.signature.to_string()
}
}
fn call_info(text: &str) -> CallInfo {
let (analysis, position) = single_file_with_position(text);
analysis.call_info(position).unwrap().unwrap()
}
#[test]
fn test_fn_signature_two_args_firstx() {
let info = call_info(
r#"fn foo(x: u32, y: u32) -> u32 {x + y}
fn bar() { foo(<|>3, ); }"#,
);
assert_eq!(info.parameters(), ["x: u32", "y: u32"]);
assert_eq!(info.active_parameter, Some(0));
}
#[test]
fn test_fn_signature_two_args_second() {
let info = call_info(
r#"fn foo(x: u32, y: u32) -> u32 {x + y}
fn bar() { foo(3, <|>); }"#,
);
assert_eq!(info.parameters(), ["x: u32", "y: u32"]);
assert_eq!(info.active_parameter, Some(1));
}
#[test]
fn test_fn_signature_two_args_empty() {
let info = call_info(
r#"fn foo(x: u32, y: u32) -> u32 {x + y}
fn bar() { foo(<|>); }"#,
);
assert_eq!(info.parameters(), ["x: u32", "y: u32"]);
assert_eq!(info.active_parameter, Some(0));
}
#[test]
fn test_fn_signature_two_args_first_generics() {
let info = call_info(
r#"fn foo<T, U: Copy + Display>(x: T, y: U) -> u32 where T: Copy + Display, U: Debug {x + y}
fn bar() { foo(<|>3, ); }"#,
);
assert_eq!(info.parameters(), ["x: T", "y: U"]);
assert_eq!(
info.label(),
r#"
fn foo<T, U: Copy + Display>(x: T, y: U) -> u32
where T: Copy + Display,
U: Debug
"#
.trim()
);
assert_eq!(info.active_parameter, Some(0));
}
#[test]
fn test_fn_signature_no_params() {
let info = call_info(
r#"fn foo<T>() -> T where T: Copy + Display {}
fn bar() { foo(<|>); }"#,
);
assert!(info.parameters().is_empty());
assert_eq!(
info.label(),
r#"
fn foo<T>() -> T
where T: Copy + Display
"#
.trim()
);
assert!(info.active_parameter.is_none());
}
#[test]
fn test_fn_signature_for_impl() {
let info = call_info(
r#"struct F; impl F { pub fn new() { F{}} }
fn bar() {let _ : F = F::new(<|>);}"#,
);
assert!(info.parameters().is_empty());
assert_eq!(info.active_parameter, None);
}
#[test]
fn test_fn_signature_for_method_self() {
let info = call_info(
r#"struct F;
impl F {
pub fn new() -> F{
F{}
}
pub fn do_it(&self) {}
}
fn bar() {
let f : F = F::new();
f.do_it(<|>);
}"#,
);
assert_eq!(info.parameters(), ["&self"]);
assert_eq!(info.active_parameter, None);
}
#[test]
fn test_fn_signature_for_method_with_arg() {
let info = call_info(
r#"struct F;
impl F {
pub fn new() -> F{
F{}
}
pub fn do_it(&self, x: i32) {}
}
fn bar() {
let f : F = F::new();
f.do_it(<|>);
}"#,
);
assert_eq!(info.parameters(), ["&self", "x: i32"]);
assert_eq!(info.active_parameter, Some(1));
}
#[test]
fn test_fn_signature_with_docs_simple() {
let info = call_info(
r#"
/// test
// non-doc-comment
fn foo(j: u32) -> u32 {
j
}
fn bar() {
let _ = foo(<|>);
}
"#,
);
assert_eq!(info.parameters(), ["j: u32"]);
assert_eq!(info.active_parameter, Some(0));
assert_eq!(info.label(), "fn foo(j: u32) -> u32");
assert_eq!(info.doc().map(|it| it.into()), Some("test".to_string()));
}
#[test]
fn test_fn_signature_with_docs() {
let info = call_info(
r#"
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, my_crate::add_one(5));
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
pub fn do() {
add_one(<|>
}"#,
);
assert_eq!(info.parameters(), ["x: i32"]);
assert_eq!(info.active_parameter, Some(0));
assert_eq!(info.label(), "pub fn add_one(x: i32) -> i32");
assert_eq!(
info.doc().map(|it| it.into()),
Some(
r#"Adds one to the number given.
# Examples
```
let five = 5;
assert_eq!(6, my_crate::add_one(5));
```"#
.to_string()
)
);
}
#[test]
fn test_fn_signature_with_docs_impl() {
let info = call_info(
r#"
struct addr;
impl addr {
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, my_crate::add_one(5));
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
}
pub fn do_it() {
addr {};
addr::add_one(<|>);
}"#,
);
assert_eq!(info.parameters(), ["x: i32"]);
assert_eq!(info.active_parameter, Some(0));
assert_eq!(info.label(), "pub fn add_one(x: i32) -> i32");
assert_eq!(
info.doc().map(|it| it.into()),
Some(
r#"Adds one to the number given.
# Examples
```
let five = 5;
assert_eq!(6, my_crate::add_one(5));
```"#
.to_string()
)
);
}
#[test]
fn test_fn_signature_with_docs_from_actix() {
let info = call_info(
r#"
struct WriteHandler<E>;
impl<E> WriteHandler<E> {
/// Method is called when writer emits error.
///
/// If this method returns `ErrorAction::Continue` writer processing
/// continues otherwise stream processing stops.
fn error(&mut self, err: E, ctx: &mut Self::Context) -> Running {
Running::Stop
}
/// Method is called when writer finishes.
///
/// By default this method stops actor's `Context`.
fn finished(&mut self, ctx: &mut Self::Context) {
ctx.stop()
}
}
pub fn foo(mut r: WriteHandler<()>) {
r.finished(<|>);
}
"#,
);
assert_eq!(info.label(), "fn finished(&mut self, ctx: &mut Self::Context)".to_string());
assert_eq!(info.parameters(), ["&mut self", "ctx: &mut Self::Context"]);
assert_eq!(info.active_parameter, Some(1));
assert_eq!(
info.doc().map(|it| it.into()),
Some(
r#"Method is called when writer finishes.
By default this method stops actor's `Context`."#
.to_string()
)
);
}
#[test]
fn call_info_bad_offset() {
covers!(call_info_bad_offset);
let (analysis, position) = single_file_with_position(
r#"fn foo(x: u32, y: u32) -> u32 {x + y}
fn bar() { foo <|> (3, ); }"#,
);
let call_info = analysis.call_info(position).unwrap();
assert!(call_info.is_none());
}
#[test]
fn test_nested_method_in_lamba() {
let info = call_info(
r#"struct Foo;
impl Foo {
fn bar(&self, _: u32) { }
}
fn bar(_: u32) { }
fn main() {
let foo = Foo;
std::thread::spawn(move || foo.bar(<|>));
}"#,
);
assert_eq!(info.parameters(), ["&self", "_: u32"]);
assert_eq!(info.active_parameter, Some(1));
assert_eq!(info.label(), "fn bar(&self, _: u32)");
}
#[test]
fn works_for_tuple_structs() {
let info = call_info(
r#"
/// A cool tuple struct
struct TS(u32, i32);
fn main() {
let s = TS(0, <|>);
}"#,
);
assert_eq!(info.label(), "struct TS(u32, i32) -> TS");
assert_eq!(info.doc().map(|it| it.into()), Some("A cool tuple struct".to_string()));
assert_eq!(info.active_parameter, Some(1));
}
#[test]
#[should_panic]
fn cant_call_named_structs() {
let _ = call_info(
r#"
struct TS { x: u32, y: i32 }
fn main() {
let s = TS(<|>);
}"#,
);
}
#[test]
fn works_for_enum_variants() {
let info = call_info(
r#"
enum E {
/// A Variant
A(i32),
/// Another
B,
/// And C
C { a: i32, b: i32 }
}
fn main() {
let a = E::A(<|>);
}
"#,
);
assert_eq!(info.label(), "E::A(0: i32)");
assert_eq!(info.doc().map(|it| it.into()), Some("A Variant".to_string()));
assert_eq!(info.active_parameter, Some(0));
}
#[test]
#[should_panic]
fn cant_call_enum_records() {
let _ = call_info(
r#"
enum E {
/// A Variant
A(i32),
/// Another
B,
/// And C
C { a: i32, b: i32 }
}
fn main() {
let a = E::C(<|>);
}
"#,
);
}
#[test]
fn fn_signature_for_macro() {
let info = call_info(
r#"
/// empty macro
macro_rules! foo {
() => {}
}
fn f() {
foo!(<|>);
}
"#,
);
assert_eq!(info.label(), "foo!()");
assert_eq!(info.doc().map(|it| it.into()), Some("empty macro".to_string()));
}
}
|