-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathrename.rs
3259 lines (2987 loc) · 71.8 KB
/
rename.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
//! Renaming functionality.
//!
//! This is mostly front-end for [`ide_db::rename`], but it also includes the
//! tests. This module also implements a couple of magic tricks, like renaming
//! `self` and to `self` (to switch between associated function and method).
use hir::{AsAssocItem, HirFileIdExt, InFile, Semantics};
use ide_db::{
defs::{Definition, NameClass, NameRefClass},
rename::{bail, format_err, source_edit_from_references, IdentifierKind},
source_change::SourceChangeBuilder,
FileId, FileRange, RootDatabase,
};
use itertools::Itertools;
use stdx::{always, never};
use syntax::{ast, AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize};
use ide_db::text_edit::TextEdit;
use crate::{FilePosition, RangeInfo, SourceChange};
pub use ide_db::rename::RenameError;
type RenameResult<T> = Result<T, RenameError>;
/// Prepares a rename. The sole job of this function is to return the TextRange of the thing that is
/// being targeted for a rename.
pub(crate) fn prepare_rename(
db: &RootDatabase,
position: FilePosition,
) -> RenameResult<RangeInfo<()>> {
let sema = Semantics::new(db);
let source_file = sema.parse_guess_edition(position.file_id);
let syntax = source_file.syntax();
let res = find_definitions(&sema, syntax, position)?
.map(|(frange, kind, def)| {
// ensure all ranges are valid
if def.range_for_rename(&sema).is_none() {
bail!("No references found at position")
}
always!(
frange.range.contains_inclusive(position.offset)
&& frange.file_id == position.file_id
);
Ok(match kind {
SyntaxKind::LIFETIME => {
TextRange::new(frange.range.start() + TextSize::from(1), frange.range.end())
}
_ => frange.range,
})
})
.reduce(|acc, cur| match (acc, cur) {
// ensure all ranges are the same
(Ok(acc_inner), Ok(cur_inner)) if acc_inner == cur_inner => Ok(acc_inner),
(e @ Err(_), _) | (_, e @ Err(_)) => e,
_ => bail!("inconsistent text range"),
});
match res {
// ensure at least one definition was found
Some(res) => res.map(|range| RangeInfo::new(range, ())),
None => bail!("No references found at position"),
}
}
// Feature: Rename
//
// Renames the item below the cursor and all of its references
//
// | Editor | Shortcut |
// |---------|----------|
// | VS Code | <kbd>F2</kbd> |
//
// 
pub(crate) fn rename(
db: &RootDatabase,
position: FilePosition,
new_name: &str,
) -> RenameResult<SourceChange> {
let sema = Semantics::new(db);
let file_id = sema
.attach_first_edition(position.file_id)
.ok_or_else(|| format_err!("No references found at position"))?;
let source_file = sema.parse(file_id);
let syntax = source_file.syntax();
let defs = find_definitions(&sema, syntax, position)?;
let alias_fallback = alias_fallback(syntax, position, new_name);
let ops: RenameResult<Vec<SourceChange>> = match alias_fallback {
Some(_) => defs
// FIXME: This can use the `ide_db::rename_reference` (or def.rename) method once we can
// properly find "direct" usages/references.
.map(|(.., def)| {
match IdentifierKind::classify(new_name)? {
IdentifierKind::Ident => (),
IdentifierKind::Lifetime => {
bail!("Cannot alias reference to a lifetime identifier")
}
IdentifierKind::Underscore => bail!("Cannot alias reference to `_`"),
};
let mut usages = def.usages(&sema).all();
// FIXME: hack - removes the usage that triggered this rename operation.
match usages.references.get_mut(&file_id).and_then(|refs| {
refs.iter()
.position(|ref_| ref_.range.contains_inclusive(position.offset))
.map(|idx| refs.remove(idx))
}) {
Some(_) => (),
None => never!(),
};
let mut source_change = SourceChange::default();
source_change.extend(usages.references.get_mut(&file_id).iter().map(|refs| {
(
position.file_id,
source_edit_from_references(refs, def, new_name, file_id.edition()),
)
}));
Ok(source_change)
})
.collect(),
None => defs
.map(|(.., def)| {
if let Definition::Local(local) = def {
if let Some(self_param) = local.as_self_param(sema.db) {
cov_mark::hit!(rename_self_to_param);
return rename_self_to_param(&sema, local, self_param, new_name);
}
if new_name == "self" {
cov_mark::hit!(rename_to_self);
return rename_to_self(&sema, local);
}
}
def.rename(&sema, new_name)
})
.collect(),
};
ops?.into_iter()
.chain(alias_fallback)
.reduce(|acc, elem| acc.merge(elem))
.ok_or_else(|| format_err!("No references found at position"))
}
/// Called by the client when it is about to rename a file.
pub(crate) fn will_rename_file(
db: &RootDatabase,
file_id: FileId,
new_name_stem: &str,
) -> Option<SourceChange> {
let sema = Semantics::new(db);
let module = sema.file_to_module_def(file_id)?;
let def = Definition::Module(module);
let mut change = def.rename(&sema, new_name_stem).ok()?;
change.file_system_edits.clear();
Some(change)
}
// FIXME: Should support `extern crate`.
fn alias_fallback(
syntax: &SyntaxNode,
FilePosition { file_id, offset }: FilePosition,
new_name: &str,
) -> Option<SourceChange> {
let use_tree = syntax
.token_at_offset(offset)
.flat_map(|syntax| syntax.parent_ancestors())
.find_map(ast::UseTree::cast)?;
let last_path_segment = use_tree.path()?.segments().last()?.name_ref()?;
if !last_path_segment.syntax().text_range().contains_inclusive(offset) {
return None;
};
let mut builder = SourceChangeBuilder::new(file_id);
match use_tree.rename() {
Some(rename) => {
let offset = rename.syntax().text_range();
builder.replace(offset, format!("as {new_name}"));
}
None => {
let offset = use_tree.syntax().text_range().end();
builder.insert(offset, format!(" as {new_name}"));
}
}
Some(builder.finish())
}
fn find_definitions(
sema: &Semantics<'_, RootDatabase>,
syntax: &SyntaxNode,
FilePosition { file_id, offset }: FilePosition,
) -> RenameResult<impl Iterator<Item = (FileRange, SyntaxKind, Definition)>> {
let token = syntax.token_at_offset(offset).find(|t| matches!(t.kind(), SyntaxKind::STRING));
if let Some((range, Some(resolution))) =
token.and_then(|token| sema.check_for_format_args_template(token, offset))
{
return Ok(vec![(
FileRange { file_id, range },
SyntaxKind::STRING,
Definition::from(resolution),
)]
.into_iter());
}
let symbols =
sema.find_nodes_at_offset_with_descend::<ast::NameLike>(syntax, offset).map(|name_like| {
let kind = name_like.syntax().kind();
let range = sema
.original_range_opt(name_like.syntax())
.ok_or_else(|| format_err!("No references found at position"))?;
let res = match &name_like {
// renaming aliases would rename the item being aliased as the HIR doesn't track aliases yet
ast::NameLike::Name(name)
if name
.syntax()
.parent().is_some_and(|it| ast::Rename::can_cast(it.kind()))
// FIXME: uncomment this once we resolve to usages to extern crate declarations
// && name
// .syntax()
// .ancestors()
// .nth(2)
// .map_or(true, |it| !ast::ExternCrate::can_cast(it.kind()))
=>
{
bail!("Renaming aliases is currently unsupported")
}
ast::NameLike::Name(name) => NameClass::classify(sema, name)
.map(|class| match class {
NameClass::Definition(it) | NameClass::ConstReference(it) => it,
NameClass::PatFieldShorthand { local_def, field_ref: _, adt_subst: _ } => {
Definition::Local(local_def)
}
})
.ok_or_else(|| format_err!("No references found at position")),
ast::NameLike::NameRef(name_ref) => {
NameRefClass::classify(sema, name_ref)
.map(|class| match class {
NameRefClass::Definition(def, _) => def,
NameRefClass::FieldShorthand { local_ref, field_ref: _, adt_subst: _ } => {
Definition::Local(local_ref)
}
NameRefClass::ExternCrateShorthand { decl, .. } => {
Definition::ExternCrateDecl(decl)
}
})
// FIXME: uncomment this once we resolve to usages to extern crate declarations
.filter(|def| !matches!(def, Definition::ExternCrateDecl(..)))
.ok_or_else(|| format_err!("No references found at position"))
.and_then(|def| {
// if the name differs from the definitions name it has to be an alias
if def
.name(sema.db).is_some_and(|it| it.as_str() != name_ref.text().trim_start_matches("r#"))
{
Err(format_err!("Renaming aliases is currently unsupported"))
} else {
Ok(def)
}
})
}
ast::NameLike::Lifetime(lifetime) => {
NameRefClass::classify_lifetime(sema, lifetime)
.and_then(|class| match class {
NameRefClass::Definition(def, _) => Some(def),
_ => None,
})
.or_else(|| {
NameClass::classify_lifetime(sema, lifetime).and_then(|it| match it {
NameClass::Definition(it) => Some(it),
_ => None,
})
})
.ok_or_else(|| format_err!("No references found at position"))
}
};
res.map(|def| (range, kind, def))
});
let res: RenameResult<Vec<_>> = symbols.collect();
match res {
Ok(v) => {
if v.is_empty() {
// FIXME: some semantic duplication between "empty vec" and "Err()"
Err(format_err!("No references found at position"))
} else {
// remove duplicates, comparing `Definition`s
Ok(v.into_iter()
.unique_by(|&(.., def)| def)
.map(|(a, b, c)| (a.into(), b, c))
.collect::<Vec<_>>()
.into_iter())
}
}
Err(e) => Err(e),
}
}
fn rename_to_self(
sema: &Semantics<'_, RootDatabase>,
local: hir::Local,
) -> RenameResult<SourceChange> {
if never!(local.is_self(sema.db)) {
bail!("rename_to_self invoked on self");
}
let fn_def = match local.parent(sema.db) {
hir::DefWithBody::Function(func) => func,
_ => bail!("Cannot rename local to self outside of function"),
};
if fn_def.self_param(sema.db).is_some() {
bail!("Method already has a self parameter");
}
let params = fn_def.assoc_fn_params(sema.db);
let first_param = params
.first()
.ok_or_else(|| format_err!("Cannot rename local to self unless it is a parameter"))?;
match first_param.as_local(sema.db) {
Some(plocal) => {
if plocal != local {
bail!("Only the first parameter may be renamed to self");
}
}
None => bail!("rename_to_self invoked on destructuring parameter"),
}
let assoc_item = fn_def
.as_assoc_item(sema.db)
.ok_or_else(|| format_err!("Cannot rename parameter to self for free function"))?;
let impl_ = match assoc_item.container(sema.db) {
hir::AssocItemContainer::Trait(_) => {
bail!("Cannot rename parameter to self for trait functions");
}
hir::AssocItemContainer::Impl(impl_) => impl_,
};
let first_param_ty = first_param.ty();
let impl_ty = impl_.self_ty(sema.db);
let (ty, self_param) = if impl_ty.remove_ref().is_some() {
// if the impl is a ref to the type we can just match the `&T` with self directly
(first_param_ty.clone(), "self")
} else {
first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
(ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
})
};
if ty != impl_ty {
bail!("Parameter type differs from impl block type");
}
let InFile { file_id, value: param_source } = sema
.source(first_param.clone())
.ok_or_else(|| format_err!("No source for parameter found"))?;
let def = Definition::Local(local);
let usages = def.usages(sema).all();
let mut source_change = SourceChange::default();
source_change.extend(usages.iter().map(|(file_id, references)| {
(file_id.into(), source_edit_from_references(references, def, "self", file_id.edition()))
}));
source_change.insert_source_edit(
file_id.original_file(sema.db),
TextEdit::replace(param_source.syntax().text_range(), String::from(self_param)),
);
Ok(source_change)
}
fn rename_self_to_param(
sema: &Semantics<'_, RootDatabase>,
local: hir::Local,
self_param: hir::SelfParam,
new_name: &str,
) -> RenameResult<SourceChange> {
if new_name == "self" {
// Let's do nothing rather than complain.
cov_mark::hit!(rename_self_to_self);
return Ok(SourceChange::default());
}
let identifier_kind = IdentifierKind::classify(new_name)?;
let InFile { file_id, value: self_param } =
sema.source(self_param).ok_or_else(|| format_err!("cannot find function source"))?;
let def = Definition::Local(local);
let usages = def.usages(sema).all();
let edit = text_edit_from_self_param(&self_param, new_name)
.ok_or_else(|| format_err!("No target type found"))?;
if usages.len() > 1 && identifier_kind == IdentifierKind::Underscore {
bail!("Cannot rename reference to `_` as it is being referenced multiple times");
}
let mut source_change = SourceChange::default();
source_change.insert_source_edit(file_id.original_file(sema.db), edit);
source_change.extend(usages.iter().map(|(file_id, references)| {
(file_id.into(), source_edit_from_references(references, def, new_name, file_id.edition()))
}));
Ok(source_change)
}
fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Option<TextEdit> {
fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
return Some(p.path()?.segment()?.name_ref()?.text().to_string());
}
None
}
match self_param.syntax().ancestors().find_map(ast::Impl::cast) {
Some(impl_def) => {
let type_name = target_type_name(&impl_def)?;
let mut replacement_text = String::from(new_name);
replacement_text.push_str(": ");
match (self_param.amp_token(), self_param.mut_token()) {
(Some(_), None) => replacement_text.push('&'),
(Some(_), Some(_)) => replacement_text.push_str("&mut "),
(_, _) => (),
};
replacement_text.push_str(type_name.as_str());
Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
}
None => {
cov_mark::hit!(rename_self_outside_of_methods);
let mut replacement_text = String::from(new_name);
replacement_text.push_str(": _");
Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
}
}
}
#[cfg(test)]
mod tests {
use expect_test::{expect, Expect};
use ide_db::source_change::SourceChange;
use ide_db::text_edit::TextEdit;
use itertools::Itertools;
use stdx::trim_indent;
use test_utils::assert_eq_text;
use crate::fixture;
use super::{RangeInfo, RenameError};
#[track_caller]
fn check(
new_name: &str,
#[rust_analyzer::rust_fixture] ra_fixture_before: &str,
#[rust_analyzer::rust_fixture] ra_fixture_after: &str,
) {
let ra_fixture_after = &trim_indent(ra_fixture_after);
let (analysis, position) = fixture::position(ra_fixture_before);
if !ra_fixture_after.starts_with("error: ") {
if let Err(err) = analysis.prepare_rename(position).unwrap() {
panic!("Prepare rename to '{new_name}' was failed: {err}")
}
}
let rename_result = analysis
.rename(position, new_name)
.unwrap_or_else(|err| panic!("Rename to '{new_name}' was cancelled: {err}"));
match rename_result {
Ok(source_change) => {
let mut text_edit_builder = TextEdit::builder();
let (&file_id, edit) = match source_change.source_file_edits.len() {
0 => return,
1 => source_change.source_file_edits.iter().next().unwrap(),
_ => panic!(),
};
for indel in edit.0.iter() {
text_edit_builder.replace(indel.delete, indel.insert.clone());
}
let mut result = analysis.file_text(file_id).unwrap().to_string();
text_edit_builder.finish().apply(&mut result);
assert_eq_text!(ra_fixture_after, &*result);
}
Err(err) => {
if ra_fixture_after.starts_with("error:") {
let error_message =
ra_fixture_after.chars().skip("error:".len()).collect::<String>();
assert_eq!(error_message.trim(), err.to_string());
} else {
panic!("Rename to '{new_name}' failed unexpectedly: {err}")
}
}
};
}
#[track_caller]
fn check_conflicts(new_name: &str, #[rust_analyzer::rust_fixture] ra_fixture: &str) {
let (analysis, position, conflicts) = fixture::annotations(ra_fixture);
let source_change = analysis.rename(position, new_name).unwrap().unwrap();
let expected_conflicts = conflicts
.into_iter()
.map(|(file_range, _)| (file_range.file_id, file_range.range))
.sorted_unstable_by_key(|(file_id, range)| (*file_id, range.start()))
.collect_vec();
let found_conflicts = source_change
.source_file_edits
.iter()
.filter(|(_, (edit, _))| edit.change_annotation().is_some())
.flat_map(|(file_id, (edit, _))| {
edit.into_iter().map(move |edit| (*file_id, edit.delete))
})
.sorted_unstable_by_key(|(file_id, range)| (*file_id, range.start()))
.collect_vec();
assert_eq!(
expected_conflicts, found_conflicts,
"rename conflicts mismatch: {source_change:#?}"
);
}
fn check_expect(
new_name: &str,
#[rust_analyzer::rust_fixture] ra_fixture: &str,
expect: Expect,
) {
let (analysis, position) = fixture::position(ra_fixture);
let source_change =
analysis.rename(position, new_name).unwrap().expect("Expect returned a RenameError");
expect.assert_eq(&filter_expect(source_change))
}
fn check_expect_will_rename_file(
new_name: &str,
#[rust_analyzer::rust_fixture] ra_fixture: &str,
expect: Expect,
) {
let (analysis, position) = fixture::position(ra_fixture);
let source_change = analysis
.will_rename_file(position.file_id, new_name)
.unwrap()
.expect("Expect returned a RenameError");
expect.assert_eq(&filter_expect(source_change))
}
fn check_prepare(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
let (analysis, position) = fixture::position(ra_fixture);
let result = analysis
.prepare_rename(position)
.unwrap_or_else(|err| panic!("PrepareRename was cancelled: {err}"));
match result {
Ok(RangeInfo { range, info: () }) => {
let source = analysis.file_text(position.file_id).unwrap();
expect.assert_eq(&format!("{range:?}: {}", &source[range]))
}
Err(RenameError(err)) => expect.assert_eq(&err),
};
}
fn filter_expect(source_change: SourceChange) -> String {
let source_file_edits = source_change
.source_file_edits
.into_iter()
.map(|(id, (text_edit, _))| (id, text_edit.into_iter().collect::<Vec<_>>()))
.collect::<Vec<_>>();
format!(
"source_file_edits: {:#?}\nfile_system_edits: {:#?}\n",
source_file_edits, source_change.file_system_edits
)
}
#[test]
fn rename_will_shadow() {
check_conflicts(
"new_name",
r#"
fn foo() {
let mut new_name = 123;
let old_name$0 = 456;
// ^^^^^^^^
new_name = 789 + new_name;
}
"#,
);
}
#[test]
fn rename_will_be_shadowed() {
check_conflicts(
"new_name",
r#"
fn foo() {
let mut old_name$0 = 456;
// ^^^^^^^^
let new_name = 123;
old_name = 789 + old_name;
// ^^^^^^^^ ^^^^^^^^
}
"#,
);
}
#[test]
fn test_prepare_rename_namelikes() {
check_prepare(r"fn name$0<'lifetime>() {}", expect![[r#"3..7: name"#]]);
check_prepare(r"fn name<'lifetime$0>() {}", expect![[r#"9..17: lifetime"#]]);
check_prepare(r"fn name<'lifetime>() { name$0(); }", expect![[r#"23..27: name"#]]);
}
#[test]
fn test_prepare_rename_in_macro() {
check_prepare(
r"macro_rules! foo {
($ident:ident) => {
pub struct $ident;
}
}
foo!(Foo$0);",
expect![[r#"83..86: Foo"#]],
);
}
#[test]
fn test_prepare_rename_keyword() {
check_prepare(r"struct$0 Foo;", expect![[r#"No references found at position"#]]);
}
#[test]
fn test_prepare_rename_tuple_field() {
check_prepare(
r#"
struct Foo(i32);
fn baz() {
let mut x = Foo(4);
x.0$0 = 5;
}
"#,
expect![[r#"No references found at position"#]],
);
}
#[test]
fn test_prepare_rename_builtin() {
check_prepare(
r#"
fn foo() {
let x: i32$0 = 0;
}
"#,
expect![[r#"No references found at position"#]],
);
}
#[test]
fn test_prepare_rename_self() {
check_prepare(
r#"
struct Foo {}
impl Foo {
fn foo(self) -> Self$0 {
self
}
}
"#,
expect![[r#"No references found at position"#]],
);
}
#[test]
fn test_rename_to_underscore() {
check("_", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let _ = 1; }"#);
}
#[test]
fn test_rename_to_raw_identifier() {
check("r#fn", r#"fn main() { let i$0 = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
}
#[test]
fn test_rename_to_invalid_identifier1() {
check(
"invalid!",
r#"fn main() { let i$0 = 1; }"#,
"error: Invalid name `invalid!`: not an identifier",
);
}
#[test]
fn test_rename_to_invalid_identifier2() {
check(
"multiple tokens",
r#"fn main() { let i$0 = 1; }"#,
"error: Invalid name `multiple tokens`: not an identifier",
);
}
#[test]
fn test_rename_to_invalid_identifier3() {
check(
"super",
r#"fn main() { let i$0 = 1; }"#,
"error: Invalid name `super`: not an identifier",
);
}
#[test]
fn test_rename_to_invalid_identifier_lifetime() {
cov_mark::check!(rename_not_an_ident_ref);
check(
"'foo",
r#"fn main() { let i$0 = 1; }"#,
"error: Invalid name `'foo`: not an identifier",
);
}
#[test]
fn test_rename_to_invalid_identifier_lifetime2() {
check(
"_",
r#"fn main<'a>(_: &'a$0 ()) {}"#,
r#"error: Invalid name `_`: not a lifetime identifier"#,
);
}
#[test]
fn test_rename_accepts_lifetime_without_apostrophe() {
check("foo", r#"fn main<'a>(_: &'a$0 ()) {}"#, r#"fn main<'foo>(_: &'foo ()) {}"#);
}
#[test]
fn test_rename_to_underscore_invalid() {
cov_mark::check!(rename_underscore_multiple);
check(
"_",
r#"fn main(foo$0: ()) {foo;}"#,
"error: Cannot rename reference to `_` as it is being referenced multiple times",
);
}
#[test]
fn test_rename_mod_invalid() {
check(
"'foo",
r#"mod foo$0 {}"#,
"error: Invalid name `'foo`: cannot rename module to 'foo",
);
}
#[test]
fn test_rename_mod_invalid_raw_ident() {
check("r#self", r#"mod foo$0 {}"#, "error: Invalid name `self`: not an identifier");
}
#[test]
fn test_rename_for_local() {
check(
"k",
r#"
fn main() {
let mut i = 1;
let j = 1;
i = i$0 + j;
{ i = 0; }
i = 5;
}
"#,
r#"
fn main() {
let mut k = 1;
let j = 1;
k = k + j;
{ k = 0; }
k = 5;
}
"#,
);
}
#[test]
fn test_rename_unresolved_reference() {
check(
"new_name",
r#"fn main() { let _ = unresolved_ref$0; }"#,
"error: No references found at position",
);
}
#[test]
fn test_rename_macro_multiple_occurrences() {
check(
"Baaah",
r#"macro_rules! foo {
($ident:ident) => {
const $ident: () = ();
struct $ident {}
};
}
foo!($0Foo);
const _: () = Foo;
const _: Foo = Foo {};
"#,
r#"
macro_rules! foo {
($ident:ident) => {
const $ident: () = ();
struct $ident {}
};
}
foo!(Baaah);
const _: () = Baaah;
const _: Baaah = Baaah {};
"#,
)
}
#[test]
fn test_rename_for_macro_args() {
check(
"b",
r#"
macro_rules! foo {($i:ident) => {$i} }
fn main() {
let a$0 = "test";
foo!(a);
}
"#,
r#"
macro_rules! foo {($i:ident) => {$i} }
fn main() {
let b = "test";
foo!(b);
}
"#,
);
}
#[test]
fn test_rename_for_macro_args_rev() {
check(
"b",
r#"
macro_rules! foo {($i:ident) => {$i} }
fn main() {
let a = "test";
foo!(a$0);
}
"#,
r#"
macro_rules! foo {($i:ident) => {$i} }
fn main() {
let b = "test";
foo!(b);
}
"#,
);
}
#[test]
fn test_rename_for_macro_define_fn() {
check(
"bar",
r#"
macro_rules! define_fn {($id:ident) => { fn $id{} }}
define_fn!(foo);
fn main() {
fo$0o();
}
"#,
r#"
macro_rules! define_fn {($id:ident) => { fn $id{} }}
define_fn!(bar);
fn main() {
bar();
}
"#,
);
}
#[test]
fn test_rename_for_macro_define_fn_rev() {
check(
"bar",
r#"
macro_rules! define_fn {($id:ident) => { fn $id{} }}
define_fn!(fo$0o);
fn main() {
foo();
}
"#,
r#"
macro_rules! define_fn {($id:ident) => { fn $id{} }}
define_fn!(bar);
fn main() {
bar();
}
"#,
);
}
#[test]
fn test_rename_for_param_inside() {
check("j", r#"fn foo(i : u32) -> u32 { i$0 }"#, r#"fn foo(j : u32) -> u32 { j }"#);
}
#[test]
fn test_rename_refs_for_fn_param() {
check("j", r#"fn foo(i$0 : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
}
#[test]
fn test_rename_for_mut_param() {
check("j", r#"fn foo(mut i$0 : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
}
#[test]
fn test_rename_struct_field() {
check(
"foo",
r#"
struct Foo { field$0: i32 }
impl Foo {
fn new(i: i32) -> Self {
Self { field: i }
}
}
"#,
r#"
struct Foo { foo: i32 }
impl Foo {
fn new(i: i32) -> Self {
Self { foo: i }
}
}
"#,
);
}
#[test]
fn test_rename_field_in_field_shorthand() {
cov_mark::check!(test_rename_field_in_field_shorthand);
check(
"field",
r#"
struct Foo { foo$0: i32 }
impl Foo {
fn new(foo: i32) -> Self {
Self { foo }
}
}
"#,
r#"
struct Foo { field: i32 }
impl Foo {
fn new(foo: i32) -> Self {
Self { field: foo }
}
}
"#,
);
}
#[test]
fn test_rename_local_in_field_shorthand() {
cov_mark::check!(test_rename_local_in_field_shorthand);
check(
"j",
r#"
struct Foo { i: i32 }
impl Foo {
fn new(i$0: i32) -> Self {
Self { i }
}
}
"#,
r#"
struct Foo { i: i32 }
impl Foo {
fn new(j: i32) -> Self {
Self { i: j }
}
}
"#,
);