Skip to content

Commit 5087af2

Browse files
committed
Auto merge of rust-lang#18362 - duncpro:goto-def-ranges, r=Veykril
feat: goto definition on range operators Closes rust-lang#18342
2 parents ca51c1e + b763913 commit 5087af2

File tree

4 files changed

+139
-17
lines changed

4 files changed

+139
-17
lines changed

src/tools/rust-analyzer/crates/hir/src/semantics.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use hir_def::{
1717
path::ModPath,
1818
resolver::{self, HasResolver, Resolver, TypeNs},
1919
type_ref::Mutability,
20-
AsMacroCall, DefWithBodyId, FunctionId, MacroId, TraitId, VariantId,
20+
AsMacroCall, DefWithBodyId, FunctionId, MacroId, StructId, TraitId, VariantId,
2121
};
2222
use hir_expand::{
2323
attrs::collect_attrs,
@@ -203,6 +203,10 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
203203
self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
204204
}
205205

206+
pub fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option<Struct> {
207+
self.imp.resolve_range_expr(range_expr).map(Struct::from)
208+
}
209+
206210
pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<Function> {
207211
self.imp.resolve_await_to_poll(await_expr).map(Function::from)
208212
}
@@ -1363,6 +1367,10 @@ impl<'db> SemanticsImpl<'db> {
13631367
self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call)
13641368
}
13651369

1370+
fn resolve_range_expr(&self, range_expr: &ast::RangeExpr) -> Option<StructId> {
1371+
self.analyze(range_expr.syntax())?.resolve_range_expr(self.db, range_expr)
1372+
}
1373+
13661374
fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<FunctionId> {
13671375
self.analyze(await_expr.syntax())?.resolve_await_to_poll(self.db, await_expr)
13681376
}

src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
//! purely for "IDE needs".
88
use std::iter::{self, once};
99

10+
use crate::{
11+
db::HirDatabase, semantics::PathResolution, Adt, AssocItem, BindingMode, BuiltinAttr,
12+
BuiltinType, Callable, Const, DeriveHelper, Field, Function, Local, Macro, ModuleDef, Static,
13+
Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, Variant,
14+
};
1015
use either::Either;
1116
use hir_def::{
1217
body::{
@@ -21,7 +26,7 @@ use hir_def::{
2126
resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
2227
type_ref::Mutability,
2328
AsMacroCall, AssocItemId, ConstId, DefWithBodyId, FieldId, FunctionId, ItemContainerId,
24-
LocalFieldId, Lookup, ModuleDefId, TraitId, VariantId,
29+
LocalFieldId, Lookup, ModuleDefId, StructId, TraitId, VariantId,
2530
};
2631
use hir_expand::{
2732
mod_path::path,
@@ -40,18 +45,13 @@ use hir_ty::{
4045
use intern::sym;
4146
use itertools::Itertools;
4247
use smallvec::SmallVec;
48+
use syntax::ast::{RangeItem, RangeOp};
4349
use syntax::{
4450
ast::{self, AstNode},
4551
SyntaxKind, SyntaxNode, TextRange, TextSize,
4652
};
4753
use triomphe::Arc;
4854

49-
use crate::{
50-
db::HirDatabase, semantics::PathResolution, Adt, AssocItem, BindingMode, BuiltinAttr,
51-
BuiltinType, Callable, Const, DeriveHelper, Field, Function, Local, Macro, ModuleDef, Static,
52-
Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, Variant,
53-
};
54-
5555
/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
5656
/// original source files. It should not be used inside the HIR itself.
5757
#[derive(Debug)]
@@ -348,6 +348,26 @@ impl SourceAnalyzer {
348348
}
349349
}
350350

351+
pub(crate) fn resolve_range_expr(
352+
&self,
353+
db: &dyn HirDatabase,
354+
range_expr: &ast::RangeExpr,
355+
) -> Option<StructId> {
356+
let path: ModPath = match (range_expr.op_kind()?, range_expr.start(), range_expr.end()) {
357+
(RangeOp::Exclusive, None, None) => path![core::ops::RangeFull],
358+
(RangeOp::Exclusive, None, Some(_)) => path![core::ops::RangeTo],
359+
(RangeOp::Exclusive, Some(_), None) => path![core::ops::RangeFrom],
360+
(RangeOp::Exclusive, Some(_), Some(_)) => path![core::ops::Range],
361+
(RangeOp::Inclusive, None, Some(_)) => path![core::ops::RangeToInclusive],
362+
(RangeOp::Inclusive, Some(_), Some(_)) => path![core::ops::RangeInclusive],
363+
364+
// [E0586] inclusive ranges must be bounded at the end
365+
(RangeOp::Inclusive, None, None) => return None,
366+
(RangeOp::Inclusive, Some(_), None) => return None,
367+
};
368+
self.resolver.resolve_known_struct(db.upcast(), &path)
369+
}
370+
351371
pub(crate) fn resolve_await_to_poll(
352372
&self,
353373
db: &dyn HirDatabase,

src/tools/rust-analyzer/crates/ide-db/src/defs.rs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,17 @@
55
66
// FIXME: this badly needs rename/rewrite (matklad, 2020-02-06).
77

8+
use crate::documentation::{Documentation, HasDocs};
9+
use crate::famous_defs::FamousDefs;
10+
use crate::RootDatabase;
811
use arrayvec::ArrayVec;
912
use either::Either;
1013
use hir::{
1114
Adt, AsAssocItem, AsExternAssocItem, AssocItem, AttributeTemplate, BuiltinAttr, BuiltinType,
1215
Const, Crate, DefWithBody, DeriveHelper, DocLinkDef, ExternAssocItem, ExternCrateDecl, Field,
1316
Function, GenericParam, HasVisibility, HirDisplay, Impl, InlineAsmOperand, Label, Local, Macro,
14-
Module, ModuleDef, Name, PathResolution, Semantics, Static, StaticLifetime, ToolModule, Trait,
15-
TraitAlias, TupleField, TypeAlias, Variant, VariantDef, Visibility,
17+
Module, ModuleDef, Name, PathResolution, Semantics, Static, StaticLifetime, Struct, ToolModule,
18+
Trait, TraitAlias, TupleField, TypeAlias, Variant, VariantDef, Visibility,
1619
};
1720
use span::Edition;
1821
use stdx::{format_to, impl_from};
@@ -21,10 +24,6 @@ use syntax::{
2124
match_ast, SyntaxKind, SyntaxNode, SyntaxToken,
2225
};
2326

24-
use crate::documentation::{Documentation, HasDocs};
25-
use crate::famous_defs::FamousDefs;
26-
use crate::RootDatabase;
27-
2827
// FIXME: a more precise name would probably be `Symbol`?
2928
#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
3029
pub enum Definition {
@@ -319,6 +318,7 @@ impl IdentClass {
319318
.map(IdentClass::NameClass)
320319
.or_else(|| NameRefClass::classify_lifetime(sema, &lifetime).map(IdentClass::NameRefClass))
321320
},
321+
ast::RangeExpr(range_expr) => OperatorClass::classify_range(sema, &range_expr).map(IdentClass::Operator),
322322
ast::AwaitExpr(await_expr) => OperatorClass::classify_await(sema, &await_expr).map(IdentClass::Operator),
323323
ast::BinExpr(bin_expr) => OperatorClass::classify_bin(sema, &bin_expr).map(IdentClass::Operator),
324324
ast::IndexExpr(index_expr) => OperatorClass::classify_index(sema, &index_expr).map(IdentClass::Operator),
@@ -372,6 +372,9 @@ impl IdentClass {
372372
| OperatorClass::Index(func)
373373
| OperatorClass::Try(func),
374374
) => res.push(Definition::Function(func)),
375+
IdentClass::Operator(OperatorClass::Range(struct0)) => {
376+
res.push(Definition::Adt(Adt::Struct(struct0)))
377+
}
375378
}
376379
res
377380
}
@@ -546,6 +549,7 @@ impl NameClass {
546549

547550
#[derive(Debug)]
548551
pub enum OperatorClass {
552+
Range(Struct),
549553
Await(Function),
550554
Prefix(Function),
551555
Index(Function),
@@ -554,6 +558,13 @@ pub enum OperatorClass {
554558
}
555559

556560
impl OperatorClass {
561+
pub fn classify_range(
562+
sema: &Semantics<'_, RootDatabase>,
563+
range_expr: &ast::RangeExpr,
564+
) -> Option<OperatorClass> {
565+
sema.resolve_range_expr(range_expr).map(OperatorClass::Range)
566+
}
567+
557568
pub fn classify_await(
558569
sema: &Semantics<'_, RootDatabase>,
559570
await_expr: &ast::AwaitExpr,

src/tools/rust-analyzer/crates/ide/src/goto_definition.rs

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use ide_db::{
1313
RootDatabase, SymbolKind,
1414
};
1515
use itertools::Itertools;
16-
1716
use span::{Edition, FileId};
1817
use syntax::{
1918
ast::{self, HasLoopBody},
@@ -418,10 +417,10 @@ fn expr_to_nav(
418417

419418
#[cfg(test)]
420419
mod tests {
420+
use crate::fixture;
421421
use ide_db::FileRange;
422422
use itertools::Itertools;
423-
424-
use crate::fixture;
423+
use syntax::SmolStr;
425424

426425
#[track_caller]
427426
fn check(ra_fixture: &str) {
@@ -450,6 +449,90 @@ mod tests {
450449
assert!(navs.is_empty(), "didn't expect this to resolve anywhere: {navs:?}")
451450
}
452451

452+
fn check_name(expected_name: &str, ra_fixture: &str) {
453+
let (analysis, position, _) = fixture::annotations(ra_fixture);
454+
let navs = analysis.goto_definition(position).unwrap().expect("no definition found").info;
455+
assert!(navs.len() < 2, "expected single navigation target but encountered {}", navs.len());
456+
let Some(target) = navs.into_iter().next() else {
457+
panic!("expected single navigation target but encountered none");
458+
};
459+
assert_eq!(target.name, SmolStr::new_inline(expected_name));
460+
}
461+
462+
#[test]
463+
fn goto_def_range() {
464+
check_name(
465+
"Range",
466+
r#"
467+
//- minicore: range
468+
let x = 0.$0.1;
469+
"#,
470+
);
471+
}
472+
473+
#[test]
474+
fn goto_def_range_from() {
475+
check_name(
476+
"RangeFrom",
477+
r#"
478+
//- minicore: range
479+
fn f(arr: &[i32]) -> &[i32] {
480+
&arr[0.$0.]
481+
}
482+
"#,
483+
);
484+
}
485+
486+
#[test]
487+
fn goto_def_range_inclusive() {
488+
check_name(
489+
"RangeInclusive",
490+
r#"
491+
//- minicore: range
492+
let x = 0.$0.=1;
493+
"#,
494+
);
495+
}
496+
497+
#[test]
498+
fn goto_def_range_full() {
499+
check_name(
500+
"RangeFull",
501+
r#"
502+
//- minicore: range
503+
fn f(arr: &[i32]) -> &[i32] {
504+
&arr[.$0.]
505+
}
506+
"#,
507+
);
508+
}
509+
510+
#[test]
511+
fn goto_def_range_to() {
512+
check_name(
513+
"RangeTo",
514+
r#"
515+
//- minicore: range
516+
fn f(arr: &[i32]) -> &[i32] {
517+
&arr[.$0.10]
518+
}
519+
"#,
520+
);
521+
}
522+
523+
#[test]
524+
fn goto_def_range_to_inclusive() {
525+
check_name(
526+
"RangeToInclusive",
527+
r#"
528+
//- minicore: range
529+
fn f(arr: &[i32]) -> &[i32] {
530+
&arr[.$0.=10]
531+
}
532+
"#,
533+
);
534+
}
535+
453536
#[test]
454537
fn goto_def_in_included_file() {
455538
check(

0 commit comments

Comments
 (0)