/
generate_function.rs
2852 lines (2603 loc) · 65.5 KB
/
generate_function.rs
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use hir::{
Adt, AsAssocItem, HasSource, HirDisplay, HirFileIdExt, Module, PathResolution, Semantics, Type,
TypeInfo,
};
use ide_db::{
base_db::FileId,
defs::{Definition, NameRefClass},
famous_defs::FamousDefs,
helpers::is_editable_crate,
path_transform::PathTransform,
source_change::SourceChangeBuilder,
FxHashMap, FxHashSet, RootDatabase, SnippetCap,
};
use itertools::Itertools;
use stdx::to_lower_snake_case;
use syntax::{
ast::{
self, edit::IndentLevel, edit_in_place::Indent, make, AstNode, CallExpr, HasArgList,
HasGenericParams, HasModuleItem, HasTypeBounds,
},
ted, SyntaxKind, SyntaxNode, TextRange, T,
};
use crate::{
utils::{convert_reference_type, find_struct_impl},
AssistContext, AssistId, AssistKind, Assists,
};
// Assist: generate_function
//
// Adds a stub function with a signature matching the function under the cursor.
//
// ```
// struct Baz;
// fn baz() -> Baz { Baz }
// fn foo() {
// bar$0("", baz());
// }
//
// ```
// ->
// ```
// struct Baz;
// fn baz() -> Baz { Baz }
// fn foo() {
// bar("", baz());
// }
//
// fn bar(arg: &str, baz: Baz) ${0:-> _} {
// todo!()
// }
//
// ```
pub(crate) fn generate_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
gen_fn(acc, ctx).or_else(|| gen_method(acc, ctx))
}
fn gen_fn(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let path_expr: ast::PathExpr = ctx.find_node_at_offset()?;
let call = path_expr.syntax().parent().and_then(ast::CallExpr::cast)?;
let path = path_expr.path()?;
let name_ref = path.segment()?.name_ref()?;
if ctx.sema.resolve_path(&path).is_some() {
// The function call already resolves, no need to add a function
return None;
}
let fn_name = &*name_ref.text();
let TargetInfo { target_module, adt_name, target, file } =
fn_target_info(ctx, path, &call, fn_name)?;
if let Some(m) = target_module {
if !is_editable_crate(m.krate(), ctx.db()) {
return None;
}
}
let function_builder = FunctionBuilder::from_call(ctx, &call, fn_name, target_module, target)?;
let text_range = call.syntax().text_range();
let label = format!("Generate {} function", function_builder.fn_name);
add_func_to_accumulator(acc, ctx, text_range, function_builder, file, adt_name, label)
}
struct TargetInfo {
target_module: Option<Module>,
adt_name: Option<hir::Name>,
target: GeneratedFunctionTarget,
file: FileId,
}
impl TargetInfo {
fn new(
target_module: Option<Module>,
adt_name: Option<hir::Name>,
target: GeneratedFunctionTarget,
file: FileId,
) -> Self {
Self { target_module, adt_name, target, file }
}
}
fn fn_target_info(
ctx: &AssistContext<'_>,
path: ast::Path,
call: &CallExpr,
fn_name: &str,
) -> Option<TargetInfo> {
match path.qualifier() {
Some(qualifier) => match ctx.sema.resolve_path(&qualifier) {
Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => {
get_fn_target_info(ctx, Some(module), call.clone())
}
Some(hir::PathResolution::Def(hir::ModuleDef::Adt(adt))) => {
if let hir::Adt::Enum(_) = adt {
// Don't suggest generating function if the name starts with an uppercase letter
if fn_name.starts_with(char::is_uppercase) {
return None;
}
}
assoc_fn_target_info(ctx, call, adt, fn_name)
}
Some(hir::PathResolution::SelfType(impl_)) => {
let adt = impl_.self_ty(ctx.db()).as_adt()?;
assoc_fn_target_info(ctx, call, adt, fn_name)
}
_ => None,
},
_ => get_fn_target_info(ctx, None, call.clone()),
}
}
fn gen_method(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let call: ast::MethodCallExpr = ctx.find_node_at_offset()?;
if ctx.sema.resolve_method_call(&call).is_some() {
return None;
}
let fn_name = call.name_ref()?;
let receiver_ty = ctx.sema.type_of_expr(&call.receiver()?)?.original().strip_references();
let adt = receiver_ty.as_adt()?;
let target_module = adt.module(ctx.sema.db);
if !is_editable_crate(target_module.krate(), ctx.db()) {
return None;
}
let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
let target = get_method_target(ctx, &impl_, &adt)?;
let function_builder = FunctionBuilder::from_method_call(
ctx,
&call,
&fn_name,
receiver_ty,
target_module,
target,
)?;
let text_range = call.syntax().text_range();
let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
let label = format!("Generate {} method", function_builder.fn_name);
add_func_to_accumulator(acc, ctx, text_range, function_builder, file, adt_name, label)
}
fn add_func_to_accumulator(
acc: &mut Assists,
ctx: &AssistContext<'_>,
text_range: TextRange,
function_builder: FunctionBuilder,
file: FileId,
adt_name: Option<hir::Name>,
label: String,
) -> Option<()> {
acc.add(AssistId("generate_function", AssistKind::Generate), label, text_range, |edit| {
edit.edit_file(file);
let target = function_builder.target.clone();
let func = function_builder.render(ctx.config.snippet_cap, edit);
if let Some(name) = adt_name {
let name = make::ty_path(make::ext::ident_path(&format!("{}", name.display(ctx.db()))));
// FIXME: adt may have generic params.
let impl_ = make::impl_(None, None, name, None, None).clone_for_update();
func.indent(IndentLevel(1));
impl_.get_or_create_assoc_item_list().add_item(func.into());
target.insert_impl_at(edit, impl_);
} else {
target.insert_fn_at(edit, func);
}
})
}
fn get_adt_source(
ctx: &AssistContext<'_>,
adt: &hir::Adt,
fn_name: &str,
) -> Option<(Option<ast::Impl>, FileId)> {
let range = adt.source(ctx.sema.db)?.syntax().original_file_range_rooted(ctx.sema.db);
let file = ctx.sema.parse(range.file_id);
let adt_source =
ctx.sema.find_node_at_offset_with_macros(file.syntax(), range.range.start())?;
find_struct_impl(ctx, &adt_source, &[fn_name.to_owned()]).map(|impl_| (impl_, range.file_id))
}
struct FunctionBuilder {
target: GeneratedFunctionTarget,
fn_name: ast::Name,
generic_param_list: Option<ast::GenericParamList>,
where_clause: Option<ast::WhereClause>,
params: ast::ParamList,
ret_type: Option<ast::RetType>,
should_focus_return_type: bool,
visibility: Visibility,
is_async: bool,
}
impl FunctionBuilder {
/// Prepares a generated function that matches `call`.
/// The function is generated in `target_module` or next to `call`
fn from_call(
ctx: &AssistContext<'_>,
call: &ast::CallExpr,
fn_name: &str,
target_module: Option<Module>,
target: GeneratedFunctionTarget,
) -> Option<Self> {
let target_module =
target_module.or_else(|| ctx.sema.scope(target.syntax()).map(|it| it.module()))?;
let current_module = ctx.sema.scope(call.syntax())?.module();
let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
let fn_name = make::name(fn_name);
let mut necessary_generic_params = FxHashSet::default();
let params = fn_args(
ctx,
target_module,
ast::CallableExpr::Call(call.clone()),
&mut necessary_generic_params,
)?;
let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
let is_async = await_expr.is_some();
let expr_for_ret_ty = await_expr.map_or_else(|| call.clone().into(), |it| it.into());
let (ret_type, should_focus_return_type) =
make_return_type(ctx, &expr_for_ret_ty, target_module, &mut necessary_generic_params);
let (generic_param_list, where_clause) =
fn_generic_params(ctx, necessary_generic_params, &target)?;
Some(Self {
target,
fn_name,
generic_param_list,
where_clause,
params,
ret_type,
should_focus_return_type,
visibility,
is_async,
})
}
fn from_method_call(
ctx: &AssistContext<'_>,
call: &ast::MethodCallExpr,
name: &ast::NameRef,
receiver_ty: Type,
target_module: Module,
target: GeneratedFunctionTarget,
) -> Option<Self> {
let current_module = ctx.sema.scope(call.syntax())?.module();
let visibility = calculate_necessary_visibility(current_module, target_module, ctx);
let fn_name = make::name(&name.text());
let mut necessary_generic_params = FxHashSet::default();
necessary_generic_params.extend(receiver_ty.generic_params(ctx.db()));
let params = fn_args(
ctx,
target_module,
ast::CallableExpr::MethodCall(call.clone()),
&mut necessary_generic_params,
)?;
let await_expr = call.syntax().parent().and_then(ast::AwaitExpr::cast);
let is_async = await_expr.is_some();
let expr_for_ret_ty = await_expr.map_or_else(|| call.clone().into(), |it| it.into());
let (ret_type, should_focus_return_type) =
make_return_type(ctx, &expr_for_ret_ty, target_module, &mut necessary_generic_params);
let (generic_param_list, where_clause) =
fn_generic_params(ctx, necessary_generic_params, &target)?;
Some(Self {
target,
fn_name,
generic_param_list,
where_clause,
params,
ret_type,
should_focus_return_type,
visibility,
is_async,
})
}
fn render(self, cap: Option<SnippetCap>, edit: &mut SourceChangeBuilder) -> ast::Fn {
let placeholder_expr = make::ext::expr_todo();
let fn_body = make::block_expr(vec![], Some(placeholder_expr));
let visibility = match self.visibility {
Visibility::None => None,
Visibility::Crate => Some(make::visibility_pub_crate()),
Visibility::Pub => Some(make::visibility_pub()),
};
let fn_def = make::fn_(
visibility,
self.fn_name,
self.generic_param_list,
self.where_clause,
self.params,
fn_body,
self.ret_type,
self.is_async,
false, // FIXME : const and unsafe are not handled yet.
false,
)
.clone_for_update();
let ret_type = fn_def.ret_type();
// PANIC: we guarantee we always create a function body with a tail expr
let tail_expr = fn_def
.body()
.expect("generated function should have a body")
.tail_expr()
.expect("function body should have a tail expression");
if let Some(cap) = cap {
if self.should_focus_return_type {
// Focus the return type if there is one
match ret_type {
Some(ret_type) => {
edit.add_placeholder_snippet(cap, ret_type.clone());
}
None => {
edit.add_placeholder_snippet(cap, tail_expr.clone());
}
}
} else {
edit.add_placeholder_snippet(cap, tail_expr.clone());
}
}
fn_def
}
}
/// Makes an optional return type along with whether the return type should be focused by the cursor.
/// If we cannot infer what the return type should be, we create a placeholder type.
///
/// The rule for whether we focus a return type or not (and thus focus the function body),
/// is rather simple:
/// * If we could *not* infer what the return type should be, focus it (so the user can fill-in
/// the correct return type).
/// * If we could infer the return type, don't focus it (and thus focus the function body) so the
/// user can change the `todo!` function body.
fn make_return_type(
ctx: &AssistContext<'_>,
expr: &ast::Expr,
target_module: Module,
necessary_generic_params: &mut FxHashSet<hir::GenericParam>,
) -> (Option<ast::RetType>, bool) {
let (ret_ty, should_focus_return_type) = {
match ctx.sema.type_of_expr(expr).map(TypeInfo::original) {
Some(ty) if ty.is_unknown() => (Some(make::ty_placeholder()), true),
None => (Some(make::ty_placeholder()), true),
Some(ty) if ty.is_unit() => (None, false),
Some(ty) => {
necessary_generic_params.extend(ty.generic_params(ctx.db()));
let rendered = ty.display_source_code(ctx.db(), target_module.into(), true);
match rendered {
Ok(rendered) => (Some(make::ty(&rendered)), false),
Err(_) => (Some(make::ty_placeholder()), true),
}
}
}
};
let ret_type = ret_ty.map(make::ret_type);
(ret_type, should_focus_return_type)
}
fn get_fn_target_info(
ctx: &AssistContext<'_>,
target_module: Option<Module>,
call: CallExpr,
) -> Option<TargetInfo> {
let (target, file) = get_fn_target(ctx, target_module, call)?;
Some(TargetInfo::new(target_module, None, target, file))
}
fn get_fn_target(
ctx: &AssistContext<'_>,
target_module: Option<Module>,
call: CallExpr,
) -> Option<(GeneratedFunctionTarget, FileId)> {
let mut file = ctx.file_id();
let target = match target_module {
Some(target_module) => {
let (in_file, target) = next_space_for_fn_in_module(ctx.db(), target_module);
file = in_file;
target
}
None => next_space_for_fn_after_call_site(ast::CallableExpr::Call(call))?,
};
Some((target, file))
}
fn get_method_target(
ctx: &AssistContext<'_>,
impl_: &Option<ast::Impl>,
adt: &Adt,
) -> Option<GeneratedFunctionTarget> {
let target = match impl_ {
Some(impl_) => GeneratedFunctionTarget::InImpl(impl_.clone()),
None => GeneratedFunctionTarget::AfterItem(adt.source(ctx.sema.db)?.syntax().value.clone()),
};
Some(target)
}
fn assoc_fn_target_info(
ctx: &AssistContext<'_>,
call: &CallExpr,
adt: hir::Adt,
fn_name: &str,
) -> Option<TargetInfo> {
let current_module = ctx.sema.scope(call.syntax())?.module();
let module = adt.module(ctx.sema.db);
let target_module = if current_module == module { None } else { Some(module) };
if current_module.krate() != module.krate() {
return None;
}
let (impl_, file) = get_adt_source(ctx, &adt, fn_name)?;
let target = get_method_target(ctx, &impl_, &adt)?;
let adt_name = if impl_.is_none() { Some(adt.name(ctx.sema.db)) } else { None };
Some(TargetInfo::new(target_module, adt_name, target, file))
}
#[derive(Clone)]
enum GeneratedFunctionTarget {
AfterItem(SyntaxNode),
InEmptyItemList(SyntaxNode),
InImpl(ast::Impl),
}
impl GeneratedFunctionTarget {
fn syntax(&self) -> &SyntaxNode {
match self {
GeneratedFunctionTarget::AfterItem(it) => it,
GeneratedFunctionTarget::InEmptyItemList(it) => it,
GeneratedFunctionTarget::InImpl(it) => it.syntax(),
}
}
fn parent(&self) -> SyntaxNode {
match self {
GeneratedFunctionTarget::AfterItem(it) => it.parent().expect("item without parent"),
GeneratedFunctionTarget::InEmptyItemList(it) => it.clone(),
GeneratedFunctionTarget::InImpl(it) => it.syntax().clone(),
}
}
fn insert_impl_at(&self, edit: &mut SourceChangeBuilder, impl_: ast::Impl) {
match self {
GeneratedFunctionTarget::AfterItem(item) => {
let item = edit.make_syntax_mut(item.clone());
let position = if item.parent().is_some() {
ted::Position::after(&item)
} else {
ted::Position::first_child_of(&item)
};
let indent = IndentLevel::from_node(&item);
let leading_ws = make::tokens::whitespace(&format!("\n{indent}"));
impl_.indent(indent);
ted::insert_all(position, vec![leading_ws.into(), impl_.syntax().clone().into()]);
}
GeneratedFunctionTarget::InEmptyItemList(item_list) => {
let item_list = edit.make_syntax_mut(item_list.clone());
let insert_after =
item_list.children_with_tokens().find_or_first(|child| child.kind() == T!['{']);
let position = match insert_after {
Some(child) => ted::Position::after(child),
None => ted::Position::first_child_of(&item_list),
};
let indent = IndentLevel::from_node(&item_list);
let leading_indent = indent + 1;
let leading_ws = make::tokens::whitespace(&format!("\n{leading_indent}"));
impl_.indent(indent);
ted::insert_all(position, vec![leading_ws.into(), impl_.syntax().clone().into()]);
}
GeneratedFunctionTarget::InImpl(_) => {
unreachable!("can't insert an impl inside an impl")
}
}
}
fn insert_fn_at(&self, edit: &mut SourceChangeBuilder, func: ast::Fn) {
match self {
GeneratedFunctionTarget::AfterItem(item) => {
let item = edit.make_syntax_mut(item.clone());
let position = if item.parent().is_some() {
ted::Position::after(&item)
} else {
ted::Position::first_child_of(&item)
};
let indent = IndentLevel::from_node(&item);
let leading_ws = make::tokens::whitespace(&format!("\n\n{indent}"));
func.indent(indent);
ted::insert_all_raw(
position,
vec![leading_ws.into(), func.syntax().clone().into()],
);
}
GeneratedFunctionTarget::InEmptyItemList(item_list) => {
let item_list = edit.make_syntax_mut(item_list.clone());
let insert_after =
item_list.children_with_tokens().find_or_first(|child| child.kind() == T!['{']);
let position = match insert_after {
Some(child) => ted::Position::after(child),
None => ted::Position::first_child_of(&item_list),
};
let indent = IndentLevel::from_node(&item_list);
let leading_indent = indent + 1;
let leading_ws = make::tokens::whitespace(&format!("\n{leading_indent}"));
let trailing_ws = make::tokens::whitespace(&format!("\n{indent}"));
func.indent(leading_indent);
ted::insert_all(
position,
vec![leading_ws.into(), func.syntax().clone().into(), trailing_ws.into()],
);
}
GeneratedFunctionTarget::InImpl(impl_) => {
let impl_ = edit.make_mut(impl_.clone());
let leading_indent = impl_.indent_level() + 1;
func.indent(leading_indent);
impl_.get_or_create_assoc_item_list().add_item(func.into());
}
}
}
}
/// Computes parameter list for the generated function.
fn fn_args(
ctx: &AssistContext<'_>,
target_module: Module,
call: ast::CallableExpr,
necessary_generic_params: &mut FxHashSet<hir::GenericParam>,
) -> Option<ast::ParamList> {
let mut arg_names = Vec::new();
let mut arg_types = Vec::new();
for arg in call.arg_list()?.args() {
arg_names.push(fn_arg_name(&ctx.sema, &arg));
arg_types.push(fn_arg_type(ctx, target_module, &arg, necessary_generic_params));
}
deduplicate_arg_names(&mut arg_names);
let params = arg_names.into_iter().zip(arg_types).map(|(name, ty)| {
make::param(make::ext::simple_ident_pat(make::name(&name)).into(), make::ty(&ty))
});
Some(make::param_list(
match call {
ast::CallableExpr::Call(_) => None,
ast::CallableExpr::MethodCall(_) => Some(make::self_param()),
},
params,
))
}
/// Gets parameter bounds and where predicates in scope and filters out irrelevant ones. Returns
/// `None` when it fails to get scope information.
///
/// See comment on `filter_unnecessary_bounds()` for what bounds we consider relevant.
///
/// NOTE: Generic parameters returned from this function may cause name clash at `target`. We don't
/// currently do anything about it because it's actually easy to resolve it after the assist: just
/// use the Rename functionality.
fn fn_generic_params(
ctx: &AssistContext<'_>,
necessary_params: FxHashSet<hir::GenericParam>,
target: &GeneratedFunctionTarget,
) -> Option<(Option<ast::GenericParamList>, Option<ast::WhereClause>)> {
if necessary_params.is_empty() {
// Not really needed but fast path.
return Some((None, None));
}
// 1. Get generic parameters (with bounds) and where predicates in scope.
let (generic_params, where_preds) = params_and_where_preds_in_scope(ctx);
// 2. Extract type parameters included in each bound.
let mut generic_params = generic_params
.into_iter()
.filter_map(|it| compute_contained_params_in_generic_param(ctx, it))
.collect();
let mut where_preds = where_preds
.into_iter()
.filter_map(|it| compute_contained_params_in_where_pred(ctx, it))
.collect();
// 3. Filter out unnecessary bounds.
filter_unnecessary_bounds(&mut generic_params, &mut where_preds, necessary_params);
filter_bounds_in_scope(&mut generic_params, &mut where_preds, ctx, target);
let generic_params: Vec<_> =
generic_params.into_iter().map(|it| it.node.clone_for_update()).collect();
let where_preds: Vec<_> =
where_preds.into_iter().map(|it| it.node.clone_for_update()).collect();
// 4. Rewrite paths
if let Some(param) = generic_params.first() {
let source_scope = ctx.sema.scope(param.syntax())?;
let target_scope = ctx.sema.scope(&target.parent())?;
if source_scope.module() != target_scope.module() {
let transform = PathTransform::generic_transformation(&target_scope, &source_scope);
let generic_params = generic_params.iter().map(|it| it.syntax());
let where_preds = where_preds.iter().map(|it| it.syntax());
transform.apply_all(generic_params.chain(where_preds));
}
}
let generic_param_list = make::generic_param_list(generic_params);
let where_clause =
if where_preds.is_empty() { None } else { Some(make::where_clause(where_preds)) };
Some((Some(generic_param_list), where_clause))
}
fn params_and_where_preds_in_scope(
ctx: &AssistContext<'_>,
) -> (Vec<ast::GenericParam>, Vec<ast::WherePred>) {
let Some(body) = containing_body(ctx) else {
return Default::default();
};
let mut generic_params = Vec::new();
let mut where_clauses = Vec::new();
// There are two items where generic parameters currently in scope may be declared: the item
// the cursor is at, and its parent (if any).
//
// We handle parent first so that their generic parameters appear first in the generic
// parameter list of the function we're generating.
let db = ctx.db();
if let Some(parent) = body.as_assoc_item(db).map(|it| it.container(db)) {
match parent {
hir::AssocItemContainer::Impl(it) => {
let (params, clauses) = get_bounds_in_scope(ctx, it);
generic_params.extend(params);
where_clauses.extend(clauses);
}
hir::AssocItemContainer::Trait(it) => {
let (params, clauses) = get_bounds_in_scope(ctx, it);
generic_params.extend(params);
where_clauses.extend(clauses);
}
}
}
// Other defs with body may inherit generic parameters from its parent, but never have their
// own generic parameters.
if let hir::DefWithBody::Function(it) = body {
let (params, clauses) = get_bounds_in_scope(ctx, it);
generic_params.extend(params);
where_clauses.extend(clauses);
}
(generic_params, where_clauses)
}
fn containing_body(ctx: &AssistContext<'_>) -> Option<hir::DefWithBody> {
let item: ast::Item = ctx.find_node_at_offset()?;
let def = match item {
ast::Item::Fn(it) => ctx.sema.to_def(&it)?.into(),
ast::Item::Const(it) => ctx.sema.to_def(&it)?.into(),
ast::Item::Static(it) => ctx.sema.to_def(&it)?.into(),
_ => return None,
};
Some(def)
}
fn get_bounds_in_scope<D>(
ctx: &AssistContext<'_>,
def: D,
) -> (impl Iterator<Item = ast::GenericParam>, impl Iterator<Item = ast::WherePred>)
where
D: HasSource,
D::Ast: HasGenericParams,
{
// This function should be only called with `Impl`, `Trait`, or `Function`, for which it's
// infallible to get source ast.
let node = ctx.sema.source(def).expect("definition's source couldn't be found").value;
let generic_params = node.generic_param_list().into_iter().flat_map(|it| it.generic_params());
let where_clauses = node.where_clause().into_iter().flat_map(|it| it.predicates());
(generic_params, where_clauses)
}
#[derive(Debug)]
struct ParamBoundWithParams {
node: ast::GenericParam,
/// Generic parameter `node` introduces.
///
/// ```text
/// impl<T> S<T> {
/// fn f<U: Trait<T>>() {}
/// ^ this
/// }
/// ```
///
/// `U` in this example.
self_ty_param: hir::GenericParam,
/// Generic parameters contained in the trait reference of this bound.
///
/// ```text
/// impl<T> S<T> {
/// fn f<U: Trait<T>>() {}
/// ^^^^^^^^ params in this part
/// }
/// ```
///
/// `T` in this example.
other_params: FxHashSet<hir::GenericParam>,
}
#[derive(Debug)]
struct WherePredWithParams {
node: ast::WherePred,
/// Generic parameters contained in the "self type" of this where predicate.
///
/// ```text
/// Struct<T, U>: Trait<T, Assoc = V>,
/// ^^^^^^^^^^^^ params in this part
/// ```
///
/// `T` and `U` in this example.
self_ty_params: FxHashSet<hir::GenericParam>,
/// Generic parameters contained in the trait reference of this where predicate.
///
/// ```text
/// Struct<T, U>: Trait<T, Assoc = V>,
/// ^^^^^^^^^^^^^^^^^^^ params in this part
/// ```
///
/// `T` and `V` in this example.
other_params: FxHashSet<hir::GenericParam>,
}
fn compute_contained_params_in_generic_param(
ctx: &AssistContext<'_>,
node: ast::GenericParam,
) -> Option<ParamBoundWithParams> {
match &node {
ast::GenericParam::TypeParam(ty) => {
let self_ty_param = ctx.sema.to_def(ty)?.into();
let other_params = ty
.type_bound_list()
.into_iter()
.flat_map(|it| it.bounds())
.flat_map(|bound| bound.syntax().descendants())
.filter_map(|node| filter_generic_params(ctx, node))
.collect();
Some(ParamBoundWithParams { node, self_ty_param, other_params })
}
ast::GenericParam::ConstParam(ct) => {
let self_ty_param = ctx.sema.to_def(ct)?.into();
Some(ParamBoundWithParams { node, self_ty_param, other_params: FxHashSet::default() })
}
ast::GenericParam::LifetimeParam(_) => {
// FIXME: It might be a good idea to handle lifetime parameters too.
None
}
}
}
fn compute_contained_params_in_where_pred(
ctx: &AssistContext<'_>,
node: ast::WherePred,
) -> Option<WherePredWithParams> {
let self_ty = node.ty()?;
let bound_list = node.type_bound_list()?;
let self_ty_params = self_ty
.syntax()
.descendants()
.filter_map(|node| filter_generic_params(ctx, node))
.collect();
let other_params = bound_list
.bounds()
.flat_map(|bound| bound.syntax().descendants())
.filter_map(|node| filter_generic_params(ctx, node))
.collect();
Some(WherePredWithParams { node, self_ty_params, other_params })
}
fn filter_generic_params(ctx: &AssistContext<'_>, node: SyntaxNode) -> Option<hir::GenericParam> {
let path = ast::Path::cast(node)?;
match ctx.sema.resolve_path(&path)? {
PathResolution::TypeParam(it) => Some(it.into()),
PathResolution::ConstParam(it) => Some(it.into()),
_ => None,
}
}
/// Filters out irrelevant bounds from `generic_params` and `where_preds`.
///
/// Say we have a trait bound `Struct<T>: Trait<U>`. Given `necessary_params`, when is it relevant
/// and when not? Some observations:
/// - When `necessary_params` contains `T`, it's likely that we want this bound, but now we have
/// an extra param to consider: `U`.
/// - On the other hand, when `necessary_params` contains `U` (but not `T`), then it's unlikely
/// that we want this bound because it doesn't really constrain `U`.
///
/// (FIXME?: The latter clause might be overstating. We may want to include the bound if the self
/// type does *not* include generic params at all - like `Option<i32>: From<U>`)
///
/// Can we make this a bit more formal? Let's define "dependency" between generic parameters and
/// trait bounds:
/// - A generic parameter `T` depends on a trait bound if `T` appears in the self type (i.e. left
/// part) of the bound.
/// - A trait bound depends on a generic parameter `T` if `T` appears in the bound.
///
/// Using the notion, what we want is all the bounds that params in `necessary_params`
/// *transitively* depend on!
///
/// Now it's not hard to solve: we build a dependency graph and compute all reachable nodes from
/// nodes that represent params in `necessary_params` by usual and boring DFS.
///
/// The time complexity is O(|generic_params| + |where_preds| + |necessary_params|).
fn filter_unnecessary_bounds(
generic_params: &mut Vec<ParamBoundWithParams>,
where_preds: &mut Vec<WherePredWithParams>,
necessary_params: FxHashSet<hir::GenericParam>,
) {
// All `self_ty_param` should be unique as they were collected from `ast::GenericParamList`s.
let param_map: FxHashMap<hir::GenericParam, usize> =
generic_params.iter().map(|it| it.self_ty_param).zip(0..).collect();
let param_count = param_map.len();
let generic_params_upper_bound = param_count + generic_params.len();
let node_count = generic_params_upper_bound + where_preds.len();
// | node index range | what the node represents |
// |-----------------------------------------|--------------------------|
// | 0..param_count | generic parameter |
// | param_count..generic_params_upper_bound | `ast::GenericParam` |
// | generic_params_upper_bound..node_count | `ast::WherePred` |
let mut graph = Graph::new(node_count);
for (pred, pred_idx) in generic_params.iter().zip(param_count..) {
let param_idx = param_map[&pred.self_ty_param];
graph.add_edge(param_idx, pred_idx);
graph.add_edge(pred_idx, param_idx);
for param in &pred.other_params {
let param_idx = param_map[param];
graph.add_edge(pred_idx, param_idx);
}
}
for (pred, pred_idx) in where_preds.iter().zip(generic_params_upper_bound..) {
for param in &pred.self_ty_params {
let param_idx = param_map[param];
graph.add_edge(param_idx, pred_idx);
graph.add_edge(pred_idx, param_idx);
}
for param in &pred.other_params {
let param_idx = param_map[param];
graph.add_edge(pred_idx, param_idx);
}
}
let starting_nodes = necessary_params.iter().flat_map(|param| param_map.get(param).copied());
let reachable = graph.compute_reachable_nodes(starting_nodes);
// Not pretty, but effective. If only there were `Vec::retain_index()`...
let mut idx = param_count;
generic_params.retain(|_| {
idx += 1;
reachable[idx - 1]
});
stdx::always!(idx == generic_params_upper_bound, "inconsistent index");
where_preds.retain(|_| {
idx += 1;
reachable[idx - 1]
});
}
/// Filters out bounds from impl if we're generating the function into the same impl we're
/// generating from.
fn filter_bounds_in_scope(
generic_params: &mut Vec<ParamBoundWithParams>,
where_preds: &mut Vec<WherePredWithParams>,
ctx: &AssistContext<'_>,
target: &GeneratedFunctionTarget,
) -> Option<()> {
let target_impl = target.parent().ancestors().find_map(ast::Impl::cast)?;
let target_impl = ctx.sema.to_def(&target_impl)?;
// It's sufficient to test only the first element of `generic_params` because of the order of
// insertion (see `params_and_where_preds_in_scope()`).
let def = generic_params.first()?.self_ty_param.parent();
if def != hir::GenericDef::Impl(target_impl) {
return None;
}
// Now we know every element that belongs to an impl would be in scope at `target`, we can
// filter them out just by looking at their parent.
generic_params.retain(|it| !matches!(it.self_ty_param.parent(), hir::GenericDef::Impl(_)));
where_preds.retain(|it| {
it.node.syntax().parent().and_then(|it| it.parent()).and_then(ast::Impl::cast).is_none()
});
Some(())
}
/// Makes duplicate argument names unique by appending incrementing numbers.
///
/// ```
/// let mut names: Vec<String> =
/// vec!["foo".into(), "foo".into(), "bar".into(), "baz".into(), "bar".into()];
/// deduplicate_arg_names(&mut names);
/// let expected: Vec<String> =
/// vec!["foo_1".into(), "foo_2".into(), "bar_1".into(), "baz".into(), "bar_2".into()];
/// assert_eq!(names, expected);
/// ```
fn deduplicate_arg_names(arg_names: &mut [String]) {
let mut arg_name_counts = FxHashMap::default();
for name in arg_names.iter() {
*arg_name_counts.entry(name).or_insert(0) += 1;
}
let duplicate_arg_names: FxHashSet<String> = arg_name_counts
.into_iter()
.filter(|(_, count)| *count >= 2)
.map(|(name, _)| name.clone())
.collect();
let mut counter_per_name = FxHashMap::default();
for arg_name in arg_names.iter_mut() {
if duplicate_arg_names.contains(arg_name) {
let counter = counter_per_name.entry(arg_name.clone()).or_insert(1);
arg_name.push('_');
arg_name.push_str(&counter.to_string());
*counter += 1;
}
}
}
fn fn_arg_name(sema: &Semantics<'_, RootDatabase>, arg_expr: &ast::Expr) -> String {
let name = (|| match arg_expr {
ast::Expr::CastExpr(cast_expr) => Some(fn_arg_name(sema, &cast_expr.expr()?)),
expr => {
let name_ref = expr
.syntax()
.descendants()
.filter_map(ast::NameRef::cast)
.filter(|name| name.ident_token().is_some())
.last()?;
if let Some(NameRefClass::Definition(Definition::Const(_) | Definition::Static(_))) =
NameRefClass::classify(sema, &name_ref)
{
return Some(name_ref.to_string().to_lowercase());
};
Some(to_lower_snake_case(&name_ref.to_string()))
}
})();
match name {
Some(mut name) if name.starts_with(|c: char| c.is_ascii_digit()) => {
name.insert_str(0, "arg");
name
}
Some(name) => name,
None => "arg".to_owned(),
}
}
fn fn_arg_type(
ctx: &AssistContext<'_>,
target_module: Module,
fn_arg: &ast::Expr,
generic_params: &mut FxHashSet<hir::GenericParam>,