-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
extract_function.rs
6173 lines (5629 loc) · 137 KB
/
extract_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 std::{iter, ops::RangeInclusive};
use ast::make;
use either::Either;
use hir::{
HasSource, HirDisplay, InFile, Local, LocalSource, ModuleDef, PathResolution, Semantics,
TypeInfo, TypeParam,
};
use ide_db::{
assists::GroupLabel,
defs::{Definition, NameRefClass},
famous_defs::FamousDefs,
helpers::mod_path_to_ast,
imports::insert_use::{insert_use, ImportScope},
search::{FileReference, ReferenceCategory, SearchScope},
source_change::SourceChangeBuilder,
syntax_helpers::node_ext::{
for_each_tail_expr, preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr,
},
FxIndexSet, RootDatabase,
};
use itertools::Itertools;
use syntax::{
ast::{
self, edit::IndentLevel, edit_in_place::Indent, AstNode, AstToken, HasGenericParams,
HasName,
},
match_ast, ted, Edition, SyntaxElement,
SyntaxKind::{self, COMMENT},
SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
};
use crate::{
assist_context::{AssistContext, Assists, TreeMutator},
utils::generate_impl,
AssistId,
};
// Assist: extract_function
//
// Extracts selected statements and comments into new function.
//
// ```
// fn main() {
// let n = 1;
// $0let m = n + 2;
// // calculate
// let k = m + n;$0
// let g = 3;
// }
// ```
// ->
// ```
// fn main() {
// let n = 1;
// fun_name(n);
// let g = 3;
// }
//
// fn $0fun_name(n: i32) {
// let m = n + 2;
// // calculate
// let k = m + n;
// }
// ```
pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let range = ctx.selection_trimmed();
if range.is_empty() {
return None;
}
let node = ctx.covering_element();
if matches!(node.kind(), T!['{'] | T!['}'] | T!['('] | T![')'] | T!['['] | T![']']) {
cov_mark::hit!(extract_function_in_braces_is_not_applicable);
return None;
}
if node.kind() == COMMENT {
cov_mark::hit!(extract_function_in_comment_is_not_applicable);
return None;
}
let node = match node {
syntax::NodeOrToken::Node(n) => n,
syntax::NodeOrToken::Token(t) => t.parent()?,
};
let body = extraction_target(&node, range)?;
let (locals_used, self_param) = body.analyze(&ctx.sema);
let anchor = if self_param.is_some() { Anchor::Method } else { Anchor::Freestanding };
let insert_after = node_to_insert_after(&body, anchor)?;
let semantics_scope = ctx.sema.scope(&insert_after)?;
let module = semantics_scope.module();
let edition = semantics_scope.krate().edition(ctx.db());
let (container_info, contains_tail_expr) = body.analyze_container(&ctx.sema, edition)?;
let ret_ty = body.return_ty(ctx)?;
let control_flow = body.external_control_flow(ctx, &container_info)?;
let ret_values = body.ret_values(ctx, node.parent().as_ref().unwrap_or(&node));
let target_range = body.text_range();
let scope = ImportScope::find_insert_use_container(&node, &ctx.sema)?;
acc.add_group(
&GroupLabel("Extract into...".to_owned()),
AssistId("extract_function", crate::AssistKind::RefactorExtract),
"Extract into function",
target_range,
move |builder| {
let outliving_locals: Vec<_> = ret_values.collect();
if stdx::never!(!outliving_locals.is_empty() && !ret_ty.is_unit()) {
// We should not have variables that outlive body if we have expression block
return;
}
let params = body.extracted_function_params(ctx, &container_info, locals_used);
let name = make_function_name(&semantics_scope);
let fun = Function {
name,
self_param,
params,
control_flow,
ret_ty,
body,
outliving_locals,
contains_tail_expr,
mods: container_info,
};
let new_indent = IndentLevel::from_node(&insert_after);
let old_indent = fun.body.indent_level();
let insert_after = builder.make_syntax_mut(insert_after);
let call_expr = make_call(ctx, &fun, old_indent);
// Map the element range to replace into the mutable version
let elements = match &fun.body {
FunctionBody::Expr(expr) => {
// expr itself becomes the replacement target
let expr = &builder.make_mut(expr.clone());
let node = SyntaxElement::Node(expr.syntax().clone());
node.clone()..=node
}
FunctionBody::Span { parent, elements, .. } => {
// Map the element range into the mutable versions
let parent = builder.make_mut(parent.clone());
let start = parent
.syntax()
.children_with_tokens()
.nth(elements.start().index())
.expect("should be able to find mutable start element");
let end = parent
.syntax()
.children_with_tokens()
.nth(elements.end().index())
.expect("should be able to find mutable end element");
start..=end
}
};
let has_impl_wrapper =
insert_after.ancestors().any(|a| a.kind() == SyntaxKind::IMPL && a != insert_after);
let fn_def = format_function(ctx, module, &fun, old_indent).clone_for_update();
if let Some(cap) = ctx.config.snippet_cap {
if let Some(name) = fn_def.name() {
builder.add_tabstop_before(cap, name);
}
}
let fn_def = match fun.self_param_adt(ctx) {
Some(adt) if anchor == Anchor::Method && !has_impl_wrapper => {
fn_def.indent(1.into());
let impl_ = generate_impl(&adt);
impl_.indent(new_indent);
impl_.get_or_create_assoc_item_list().add_item(fn_def.into());
impl_.syntax().clone()
}
_ => {
fn_def.indent(new_indent);
fn_def.syntax().clone()
}
};
// There are external control flows
if fun
.control_flow
.kind
.is_some_and(|kind| matches!(kind, FlowKind::Break(_, _) | FlowKind::Continue(_)))
{
let scope = match scope {
ImportScope::File(it) => ImportScope::File(builder.make_mut(it)),
ImportScope::Module(it) => ImportScope::Module(builder.make_mut(it)),
ImportScope::Block(it) => ImportScope::Block(builder.make_mut(it)),
};
let control_flow_enum =
FamousDefs(&ctx.sema, module.krate()).core_ops_ControlFlow();
if let Some(control_flow_enum) = control_flow_enum {
let mod_path = module.find_use_path(
ctx.sema.db,
ModuleDef::from(control_flow_enum),
ctx.config.insert_use.prefix_kind,
ctx.config.import_path_config(),
);
if let Some(mod_path) = mod_path {
insert_use(
&scope,
mod_path_to_ast(&mod_path, edition),
&ctx.config.insert_use,
);
}
}
}
// Replace the call site with the call to the new function
fixup_call_site(builder, &fun.body);
ted::replace_all(elements, vec![call_expr.into()]);
// Insert the newly extracted function (or impl)
ted::insert_all_raw(
ted::Position::after(insert_after),
vec![make::tokens::whitespace(&format!("\n\n{new_indent}")).into(), fn_def.into()],
);
},
)
}
fn make_function_name(semantics_scope: &hir::SemanticsScope<'_>) -> ast::NameRef {
let mut names_in_scope = vec![];
semantics_scope.process_all_names(&mut |name, _| {
names_in_scope.push(
name.display(
semantics_scope.db.upcast(),
semantics_scope.krate().edition(semantics_scope.db),
)
.to_string(),
)
});
let default_name = "fun_name";
let mut name = default_name.to_owned();
let mut counter = 0;
while names_in_scope.contains(&name) {
counter += 1;
name = format!("{default_name}{counter}")
}
make::name_ref(&name)
}
/// Try to guess what user wants to extract
///
/// We have basically have two cases:
/// * We want whole node, like `loop {}`, `2 + 2`, `{ let n = 1; }` exprs.
/// Then we can use `ast::Expr`
/// * We want a few statements for a block. E.g.
/// ```rust,no_run
/// fn foo() -> i32 {
/// let m = 1;
/// $0
/// let n = 2;
/// let k = 3;
/// k + n
/// $0
/// }
/// ```
///
fn extraction_target(node: &SyntaxNode, selection_range: TextRange) -> Option<FunctionBody> {
if let Some(stmt) = ast::Stmt::cast(node.clone()) {
return match stmt {
ast::Stmt::Item(_) => None,
ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => FunctionBody::from_range(
node.parent().and_then(ast::StmtList::cast)?,
node.text_range(),
),
};
}
// Covering element returned the parent block of one or multiple statements that have been selected
if let Some(stmt_list) = ast::StmtList::cast(node.clone()) {
if let Some(block_expr) = stmt_list.syntax().parent().and_then(ast::BlockExpr::cast) {
if block_expr.syntax().text_range() == selection_range {
return FunctionBody::from_expr(block_expr.into());
}
}
// Extract the full statements.
return FunctionBody::from_range(stmt_list, selection_range);
}
let expr = ast::Expr::cast(node.clone())?;
// A node got selected fully
if node.text_range() == selection_range {
return FunctionBody::from_expr(expr);
}
node.ancestors().find_map(ast::Expr::cast).and_then(FunctionBody::from_expr)
}
#[derive(Debug)]
struct Function {
name: ast::NameRef,
self_param: Option<ast::SelfParam>,
params: Vec<Param>,
control_flow: ControlFlow,
ret_ty: RetType,
body: FunctionBody,
outliving_locals: Vec<OutlivedLocal>,
/// Whether at least one of the container's tail expr is contained in the range we're extracting.
contains_tail_expr: bool,
mods: ContainerInfo,
}
#[derive(Debug)]
struct Param {
var: Local,
ty: hir::Type,
move_local: bool,
requires_mut: bool,
is_copy: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParamKind {
Value,
MutValue,
SharedRef,
MutRef,
}
#[derive(Debug)]
enum FunType {
Unit,
Single(hir::Type),
Tuple(Vec<hir::Type>),
}
/// Where to put extracted function definition
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum Anchor {
/// Extract free function and put right after current top-level function
Freestanding,
/// Extract method and put right after current function in the impl-block
Method,
}
// FIXME: ControlFlow and ContainerInfo both track some function modifiers, feels like these two should
// probably be merged somehow.
#[derive(Debug)]
struct ControlFlow {
kind: Option<FlowKind>,
is_async: bool,
is_unsafe: bool,
}
/// The thing whose expression we are extracting from. Can be a function, const, static, const arg, ...
#[derive(Clone, Debug)]
struct ContainerInfo {
is_const: bool,
parent_loop: Option<SyntaxNode>,
/// The function's return type, const's type etc.
ret_type: Option<hir::Type>,
generic_param_lists: Vec<ast::GenericParamList>,
where_clauses: Vec<ast::WhereClause>,
edition: Edition,
}
/// Control flow that is exported from extracted function
///
/// E.g.:
/// ```rust,no_run
/// loop {
/// $0
/// if 42 == 42 {
/// break;
/// }
/// $0
/// }
/// ```
#[derive(Debug, Clone)]
enum FlowKind {
/// Return with value (`return $expr;`)
Return(Option<ast::Expr>),
Try {
kind: TryKind,
},
/// Break with label and value (`break 'label $expr;`)
Break(Option<ast::Lifetime>, Option<ast::Expr>),
/// Continue with label (`continue 'label;`)
Continue(Option<ast::Lifetime>),
}
#[derive(Debug, Clone)]
enum TryKind {
Option,
Result { ty: hir::Type },
}
#[derive(Debug)]
enum RetType {
Expr(hir::Type),
Stmt,
}
impl RetType {
fn is_unit(&self) -> bool {
match self {
RetType::Expr(ty) => ty.is_unit(),
RetType::Stmt => true,
}
}
}
/// Semantically same as `ast::Expr`, but preserves identity when using only part of the Block
/// This is the future function body, the part that is being extracted.
#[derive(Debug)]
enum FunctionBody {
Expr(ast::Expr),
Span { parent: ast::StmtList, elements: RangeInclusive<SyntaxElement>, text_range: TextRange },
}
#[derive(Debug)]
struct OutlivedLocal {
local: Local,
mut_usage_outside_body: bool,
}
/// Container of local variable usages
///
/// Semantically same as `UsageSearchResult`, but provides more convenient interface
struct LocalUsages(ide_db::search::UsageSearchResult);
impl LocalUsages {
fn find_local_usages(ctx: &AssistContext<'_>, var: Local) -> Self {
Self(
Definition::Local(var)
.usages(&ctx.sema)
.in_scope(&SearchScope::single_file(ctx.file_id()))
.all(),
)
}
fn iter(&self) -> impl Iterator<Item = &FileReference> + '_ {
self.0.iter().flat_map(|(_, rs)| rs)
}
}
impl Function {
fn return_type(&self, ctx: &AssistContext<'_>) -> FunType {
match &self.ret_ty {
RetType::Expr(ty) if ty.is_unit() => FunType::Unit,
RetType::Expr(ty) => FunType::Single(ty.clone()),
RetType::Stmt => match self.outliving_locals.as_slice() {
[] => FunType::Unit,
[var] => FunType::Single(var.local.ty(ctx.db())),
vars => {
let types = vars.iter().map(|v| v.local.ty(ctx.db())).collect();
FunType::Tuple(types)
}
},
}
}
fn self_param_adt(&self, ctx: &AssistContext<'_>) -> Option<ast::Adt> {
let self_param = self.self_param.as_ref()?;
let def = ctx.sema.to_def(self_param)?;
let adt = def.ty(ctx.db()).strip_references().as_adt()?;
let InFile { file_id: _, value } = adt.source(ctx.db())?;
Some(value)
}
}
impl ParamKind {
fn is_ref(&self) -> bool {
matches!(self, ParamKind::SharedRef | ParamKind::MutRef)
}
}
impl Param {
fn kind(&self) -> ParamKind {
match (self.move_local, self.requires_mut, self.is_copy) {
(false, true, _) => ParamKind::MutRef,
(false, false, false) => ParamKind::SharedRef,
(true, true, _) => ParamKind::MutValue,
(_, false, _) => ParamKind::Value,
}
}
fn to_arg(&self, ctx: &AssistContext<'_>, edition: Edition) -> ast::Expr {
let var = path_expr_from_local(ctx, self.var, edition);
match self.kind() {
ParamKind::Value | ParamKind::MutValue => var,
ParamKind::SharedRef => make::expr_ref(var, false),
ParamKind::MutRef => make::expr_ref(var, true),
}
}
fn to_param(
&self,
ctx: &AssistContext<'_>,
module: hir::Module,
edition: Edition,
) -> ast::Param {
let var = self.var.name(ctx.db()).display(ctx.db(), edition).to_string();
let var_name = make::name(&var);
let pat = match self.kind() {
ParamKind::MutValue => make::ident_pat(false, true, var_name),
ParamKind::Value | ParamKind::SharedRef | ParamKind::MutRef => {
make::ext::simple_ident_pat(var_name)
}
};
let ty = make_ty(&self.ty, ctx, module);
let ty = match self.kind() {
ParamKind::Value | ParamKind::MutValue => ty,
ParamKind::SharedRef => make::ty_ref(ty, false),
ParamKind::MutRef => make::ty_ref(ty, true),
};
make::param(pat.into(), ty)
}
}
impl TryKind {
fn of_ty(ty: hir::Type, ctx: &AssistContext<'_>, edition: Edition) -> Option<TryKind> {
if ty.is_unknown() {
// We favour Result for `expr?`
return Some(TryKind::Result { ty });
}
let adt = ty.as_adt()?;
let name = adt.name(ctx.db());
// FIXME: use lang items to determine if it is std type or user defined
// E.g. if user happens to define type named `Option`, we would have false positive
let name = &name.display(ctx.db(), edition).to_string();
match name.as_str() {
"Option" => Some(TryKind::Option),
"Result" => Some(TryKind::Result { ty }),
_ => None,
}
}
}
impl FlowKind {
fn make_result_handler(&self, expr: Option<ast::Expr>) -> ast::Expr {
match self {
FlowKind::Return(_) => make::expr_return(expr),
FlowKind::Break(label, _) => make::expr_break(label.clone(), expr),
FlowKind::Try { .. } => {
stdx::never!("cannot have result handler with try");
expr.unwrap_or_else(|| make::expr_return(None))
}
FlowKind::Continue(label) => {
stdx::always!(expr.is_none(), "continue with value is not possible");
make::expr_continue(label.clone())
}
}
}
fn expr_ty(&self, ctx: &AssistContext<'_>) -> Option<hir::Type> {
match self {
FlowKind::Return(Some(expr)) | FlowKind::Break(_, Some(expr)) => {
ctx.sema.type_of_expr(expr).map(TypeInfo::adjusted)
}
FlowKind::Try { .. } => {
stdx::never!("try does not have defined expr_ty");
None
}
_ => None,
}
}
}
impl FunctionBody {
fn parent(&self) -> Option<SyntaxNode> {
match self {
FunctionBody::Expr(expr) => expr.syntax().parent(),
FunctionBody::Span { parent, .. } => Some(parent.syntax().clone()),
}
}
fn node(&self) -> &SyntaxNode {
match self {
FunctionBody::Expr(e) => e.syntax(),
FunctionBody::Span { parent, .. } => parent.syntax(),
}
}
fn extracted_from_trait_impl(&self) -> bool {
match self.node().ancestors().find_map(ast::Impl::cast) {
Some(c) => c.trait_().is_some(),
None => false,
}
}
fn descendants(&self) -> impl Iterator<Item = SyntaxNode> {
match self {
FunctionBody::Expr(expr) => expr.syntax().descendants(),
FunctionBody::Span { parent, .. } => parent.syntax().descendants(),
}
}
fn descendant_paths(&self) -> impl Iterator<Item = ast::Path> {
self.descendants().filter_map(|node| {
match_ast! {
match node {
ast::Path(it) => Some(it),
_ => None
}
}
})
}
fn from_expr(expr: ast::Expr) -> Option<Self> {
match expr {
ast::Expr::BreakExpr(it) => it.expr().map(Self::Expr),
ast::Expr::ReturnExpr(it) => it.expr().map(Self::Expr),
ast::Expr::BlockExpr(it) if !it.is_standalone() => None,
expr => Some(Self::Expr(expr)),
}
}
fn from_range(parent: ast::StmtList, selected: TextRange) -> Option<FunctionBody> {
let full_body = parent.syntax().children_with_tokens();
// Get all of the elements intersecting with the selection
let mut stmts_in_selection = full_body
.filter(|it| ast::Stmt::can_cast(it.kind()) || it.kind() == COMMENT)
.filter(|it| selected.intersect(it.text_range()).filter(|it| !it.is_empty()).is_some());
let first_element = stmts_in_selection.next();
// If the tail expr is part of the selection too, make that the last element
// Otherwise use the last stmt
let last_element = if let Some(tail_expr) =
parent.tail_expr().filter(|it| selected.intersect(it.syntax().text_range()).is_some())
{
Some(tail_expr.syntax().clone().into())
} else {
stmts_in_selection.last()
};
let elements = match (first_element, last_element) {
(None, _) => {
cov_mark::hit!(extract_function_empty_selection_is_not_applicable);
return None;
}
(Some(first), None) => first.clone()..=first,
(Some(first), Some(last)) => first..=last,
};
let text_range = elements.start().text_range().cover(elements.end().text_range());
Some(Self::Span { parent, elements, text_range })
}
fn indent_level(&self) -> IndentLevel {
match &self {
FunctionBody::Expr(expr) => IndentLevel::from_node(expr.syntax()),
FunctionBody::Span { parent, .. } => IndentLevel::from_node(parent.syntax()) + 1,
}
}
fn tail_expr(&self) -> Option<ast::Expr> {
match &self {
FunctionBody::Expr(expr) => Some(expr.clone()),
FunctionBody::Span { parent, text_range, .. } => {
let tail_expr = parent.tail_expr()?;
text_range.contains_range(tail_expr.syntax().text_range()).then_some(tail_expr)
}
}
}
fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
match self {
FunctionBody::Expr(expr) => walk_expr(expr, cb),
FunctionBody::Span { parent, text_range, .. } => {
parent
.statements()
.filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
.filter_map(|stmt| match stmt {
ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
ast::Stmt::Item(_) => None,
ast::Stmt::LetStmt(stmt) => stmt.initializer(),
})
.for_each(|expr| walk_expr(&expr, cb));
if let Some(expr) = parent
.tail_expr()
.filter(|it| text_range.contains_range(it.syntax().text_range()))
{
walk_expr(&expr, cb);
}
}
}
}
fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
match self {
FunctionBody::Expr(expr) => preorder_expr(expr, cb),
FunctionBody::Span { parent, text_range, .. } => {
parent
.statements()
.filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
.filter_map(|stmt| match stmt {
ast::Stmt::ExprStmt(expr_stmt) => expr_stmt.expr(),
ast::Stmt::Item(_) => None,
ast::Stmt::LetStmt(stmt) => stmt.initializer(),
})
.for_each(|expr| preorder_expr(&expr, cb));
if let Some(expr) = parent
.tail_expr()
.filter(|it| text_range.contains_range(it.syntax().text_range()))
{
preorder_expr(&expr, cb);
}
}
}
}
fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
match self {
FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
FunctionBody::Span { parent, text_range, .. } => {
parent
.statements()
.filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
.for_each(|stmt| match stmt {
ast::Stmt::ExprStmt(expr_stmt) => {
if let Some(expr) = expr_stmt.expr() {
walk_patterns_in_expr(&expr, cb)
}
}
ast::Stmt::Item(_) => (),
ast::Stmt::LetStmt(stmt) => {
if let Some(pat) = stmt.pat() {
walk_pat(&pat, cb);
}
if let Some(expr) = stmt.initializer() {
walk_patterns_in_expr(&expr, cb);
}
}
});
if let Some(expr) = parent
.tail_expr()
.filter(|it| text_range.contains_range(it.syntax().text_range()))
{
walk_patterns_in_expr(&expr, cb);
}
}
}
}
fn text_range(&self) -> TextRange {
match self {
FunctionBody::Expr(expr) => expr.syntax().text_range(),
&FunctionBody::Span { text_range, .. } => text_range,
}
}
fn contains_range(&self, range: TextRange) -> bool {
self.text_range().contains_range(range)
}
fn precedes_range(&self, range: TextRange) -> bool {
self.text_range().end() <= range.start()
}
fn contains_node(&self, node: &SyntaxNode) -> bool {
self.contains_range(node.text_range())
}
}
impl FunctionBody {
/// Analyzes a function body, returning the used local variables that are referenced in it as well as
/// whether it contains an await expression.
fn analyze(
&self,
sema: &Semantics<'_, RootDatabase>,
) -> (FxIndexSet<Local>, Option<ast::SelfParam>) {
let mut self_param = None;
let mut res = FxIndexSet::default();
let mut add_name_if_local = |name_ref: Option<_>| {
let local_ref =
match name_ref.and_then(|name_ref| NameRefClass::classify(sema, &name_ref)) {
Some(
NameRefClass::Definition(Definition::Local(local_ref), _)
| NameRefClass::FieldShorthand { local_ref, field_ref: _, adt_subst: _ },
) => local_ref,
_ => return,
};
let InFile { file_id, value } = local_ref.primary_source(sema.db).source;
// locals defined inside macros are not relevant to us
if !file_id.is_macro() {
match value {
Either::Right(it) => {
self_param.replace(it);
}
Either::Left(_) => {
res.insert(local_ref);
}
}
}
};
self.walk_expr(&mut |expr| match expr {
ast::Expr::PathExpr(path_expr) => {
add_name_if_local(path_expr.path().and_then(|it| it.as_single_name_ref()))
}
ast::Expr::ClosureExpr(closure_expr) => {
if let Some(body) = closure_expr.body() {
body.syntax()
.descendants()
.map(ast::NameRef::cast)
.for_each(&mut add_name_if_local);
}
}
ast::Expr::MacroExpr(expr) => {
if let Some(tt) = expr.macro_call().and_then(|call| call.token_tree()) {
tt.syntax()
.descendants_with_tokens()
.filter_map(SyntaxElement::into_token)
.filter(|it| matches!(it.kind(), SyntaxKind::IDENT | T![self]))
.flat_map(|t| sema.descend_into_macros_exact(t))
.for_each(|t| add_name_if_local(t.parent().and_then(ast::NameRef::cast)));
}
}
_ => (),
});
(res, self_param)
}
fn analyze_container(
&self,
sema: &Semantics<'_, RootDatabase>,
edition: Edition,
) -> Option<(ContainerInfo, bool)> {
let mut ancestors = self.parent()?.ancestors();
let infer_expr_opt = |expr| sema.type_of_expr(&expr?).map(TypeInfo::adjusted);
let mut parent_loop = None;
let mut set_parent_loop = |loop_: &dyn ast::HasLoopBody| {
if loop_
.loop_body()
.map_or(false, |it| it.syntax().text_range().contains_range(self.text_range()))
{
parent_loop.get_or_insert(loop_.syntax().clone());
}
};
let (is_const, expr, ty) = loop {
let anc = ancestors.next()?;
break match_ast! {
match anc {
ast::ClosureExpr(closure) => (false, closure.body(), infer_expr_opt(closure.body())),
ast::BlockExpr(block_expr) => {
let (constness, block) = match block_expr.modifier() {
Some(ast::BlockModifier::Const(_)) => (true, block_expr),
Some(ast::BlockModifier::Try(_)) => (false, block_expr),
Some(ast::BlockModifier::Label(label)) if label.lifetime().is_some() => (false, block_expr),
_ => continue,
};
let expr = Some(ast::Expr::BlockExpr(block));
(constness, expr.clone(), infer_expr_opt(expr))
},
ast::Fn(fn_) => {
let func = sema.to_def(&fn_)?;
let mut ret_ty = func.ret_type(sema.db);
if func.is_async(sema.db) {
if let Some(async_ret) = func.async_ret_type(sema.db) {
ret_ty = async_ret;
}
}
(fn_.const_token().is_some(), fn_.body().map(ast::Expr::BlockExpr), Some(ret_ty))
},
ast::Static(statik) => {
(true, statik.body(), Some(sema.to_def(&statik)?.ty(sema.db)))
},
ast::ConstArg(ca) => {
(true, ca.expr(), infer_expr_opt(ca.expr()))
},
ast::Const(konst) => {
(true, konst.body(), Some(sema.to_def(&konst)?.ty(sema.db)))
},
ast::ConstParam(cp) => {
(true, cp.default_val()?.expr(), Some(sema.to_def(&cp)?.ty(sema.db)))
},
ast::ConstBlockPat(cbp) => {
let expr = cbp.block_expr().map(ast::Expr::BlockExpr);
(true, expr.clone(), infer_expr_opt(expr))
},
ast::Variant(__) => return None,
ast::Meta(__) => return None,
ast::LoopExpr(it) => {
set_parent_loop(&it);
continue;
},
ast::ForExpr(it) => {
set_parent_loop(&it);
continue;
},
ast::WhileExpr(it) => {
set_parent_loop(&it);
continue;
},
_ => continue,
}
};
};
let expr = expr?;
let contains_tail_expr = if let Some(body_tail) = self.tail_expr() {
let mut contains_tail_expr = false;
let tail_expr_range = body_tail.syntax().text_range();
for_each_tail_expr(&expr, &mut |e| {
if tail_expr_range.contains_range(e.syntax().text_range()) {
contains_tail_expr = true;
}
});
contains_tail_expr
} else {
false
};
let parent = self.parent()?;
let parents = generic_parents(&parent);
let generic_param_lists = parents.iter().filter_map(|it| it.generic_param_list()).collect();
let where_clauses = parents.iter().filter_map(|it| it.where_clause()).collect();
Some((
ContainerInfo {
is_const,
parent_loop,
ret_type: ty,
generic_param_lists,
where_clauses,
edition,
},
contains_tail_expr,
))
}
fn return_ty(&self, ctx: &AssistContext<'_>) -> Option<RetType> {
match self.tail_expr() {
Some(expr) => ctx.sema.type_of_expr(&expr).map(TypeInfo::original).map(RetType::Expr),
None => Some(RetType::Stmt),
}
}
/// Local variables defined inside `body` that are accessed outside of it
fn ret_values<'a>(
&self,
ctx: &'a AssistContext<'_>,
parent: &SyntaxNode,
) -> impl Iterator<Item = OutlivedLocal> + 'a {
let parent = parent.clone();
let range = self.text_range();
locals_defined_in_body(&ctx.sema, self)
.into_iter()
.filter_map(move |local| local_outlives_body(ctx, range, local, &parent))
}
/// Analyses the function body for external control flow.
fn external_control_flow(
&self,
ctx: &AssistContext<'_>,
container_info: &ContainerInfo,
) -> Option<ControlFlow> {
let mut ret_expr = None;
let mut try_expr = None;
let mut break_expr = None;
let mut continue_expr = None;
let mut is_async = false;
let mut _is_unsafe = false;
let mut unsafe_depth = 0;
let mut loop_depth = 0;
self.preorder_expr(&mut |expr| {
let expr = match expr {
WalkEvent::Enter(e) => e,
WalkEvent::Leave(expr) => {
match expr {
ast::Expr::LoopExpr(_)
| ast::Expr::ForExpr(_)
| ast::Expr::WhileExpr(_) => loop_depth -= 1,