ide/
moniker.rs

1//! This module generates [moniker](https://microsoft.github.io/language-server-protocol/specifications/lsif/0.6.0/specification/#exportsImports)
2//! for LSIF and LSP.
3
4use core::fmt;
5
6use hir::{Adt, AsAssocItem, Crate, HirDisplay, MacroKind, Semantics};
7use ide_db::{
8    FilePosition, RootDatabase,
9    base_db::{CrateOrigin, LangCrateOrigin},
10    defs::{Definition, IdentClass},
11    helpers::pick_best_token,
12};
13use itertools::Itertools;
14use syntax::{AstNode, SyntaxKind::*, T};
15
16use crate::{RangeInfo, doc_links::token_as_doc_comment, parent_module::crates_for};
17
18#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum MonikerDescriptorKind {
20    Namespace,
21    Type,
22    Term,
23    Method,
24    TypeParameter,
25    Parameter,
26    Macro,
27    Meta,
28}
29
30// Subset of scip_types::SymbolInformation::Kind
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub enum SymbolInformationKind {
33    AssociatedType,
34    Attribute,
35    Constant,
36    Enum,
37    EnumMember,
38    Field,
39    Function,
40    Macro,
41    Method,
42    Module,
43    Parameter,
44    SelfParameter,
45    StaticMethod,
46    StaticVariable,
47    Struct,
48    Trait,
49    TraitMethod,
50    Type,
51    TypeAlias,
52    TypeParameter,
53    Union,
54    Variable,
55}
56
57impl From<SymbolInformationKind> for MonikerDescriptorKind {
58    fn from(value: SymbolInformationKind) -> Self {
59        match value {
60            SymbolInformationKind::AssociatedType => Self::Type,
61            SymbolInformationKind::Attribute => Self::Meta,
62            SymbolInformationKind::Constant => Self::Term,
63            SymbolInformationKind::Enum => Self::Type,
64            SymbolInformationKind::EnumMember => Self::Type,
65            SymbolInformationKind::Field => Self::Term,
66            SymbolInformationKind::Function => Self::Method,
67            SymbolInformationKind::Macro => Self::Macro,
68            SymbolInformationKind::Method => Self::Method,
69            SymbolInformationKind::Module => Self::Namespace,
70            SymbolInformationKind::Parameter => Self::Parameter,
71            SymbolInformationKind::SelfParameter => Self::Parameter,
72            SymbolInformationKind::StaticMethod => Self::Method,
73            SymbolInformationKind::StaticVariable => Self::Term,
74            SymbolInformationKind::Struct => Self::Type,
75            SymbolInformationKind::Trait => Self::Type,
76            SymbolInformationKind::TraitMethod => Self::Method,
77            SymbolInformationKind::Type => Self::Type,
78            SymbolInformationKind::TypeAlias => Self::Type,
79            SymbolInformationKind::TypeParameter => Self::TypeParameter,
80            SymbolInformationKind::Union => Self::Type,
81            SymbolInformationKind::Variable => Self::Term,
82        }
83    }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
87pub struct MonikerDescriptor {
88    pub name: String,
89    pub desc: MonikerDescriptorKind,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub struct MonikerIdentifier {
94    pub crate_name: String,
95    pub description: Vec<MonikerDescriptor>,
96}
97
98impl fmt::Display for MonikerIdentifier {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(&self.crate_name)?;
101        f.write_fmt(format_args!("::{}", self.description.iter().map(|x| &x.name).join("::")))
102    }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub enum MonikerKind {
107    Import,
108    Export,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Hash)]
112pub enum MonikerResult {
113    /// Uniquely identifies a definition.
114    Moniker(Moniker),
115    /// Specifies that the definition is a local, and so does not have a unique identifier. Provides
116    /// a unique identifier for the container.
117    Local { enclosing_moniker: Option<Moniker> },
118}
119
120impl MonikerResult {
121    pub fn from_def(db: &RootDatabase, def: Definition, from_crate: Crate) -> Option<Self> {
122        def_to_moniker(db, def, from_crate)
123    }
124}
125
126/// Information which uniquely identifies a definition which might be referenceable outside of the
127/// source file. Visibility declarations do not affect presence.
128#[derive(Debug, Clone, PartialEq, Eq, Hash)]
129pub struct Moniker {
130    pub identifier: MonikerIdentifier,
131    pub kind: MonikerKind,
132    pub package_information: PackageInformation,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq, Hash)]
136pub struct PackageInformation {
137    pub name: String,
138    pub repo: Option<String>,
139    pub version: Option<String>,
140}
141
142pub(crate) fn moniker(
143    db: &RootDatabase,
144    FilePosition { file_id, offset }: FilePosition,
145) -> Option<RangeInfo<Vec<MonikerResult>>> {
146    let sema = &Semantics::new(db);
147    let file = sema.parse_guess_edition(file_id).syntax().clone();
148    let current_crate: hir::Crate = crates_for(db, file_id).pop()?.into();
149    let original_token = pick_best_token(file.token_at_offset(offset), |kind| match kind {
150        IDENT
151        | INT_NUMBER
152        | LIFETIME_IDENT
153        | T![self]
154        | T![super]
155        | T![crate]
156        | T![Self]
157        | COMMENT => 2,
158        kind if kind.is_trivia() => 0,
159        _ => 1,
160    })?;
161    if let Some(doc_comment) = token_as_doc_comment(&original_token) {
162        return doc_comment.get_definition_with_descend_at(sema, offset, |def, _, _| {
163            let m = def_to_moniker(db, def, current_crate)?;
164            Some(RangeInfo::new(original_token.text_range(), vec![m]))
165        });
166    }
167    let navs = sema
168        .descend_into_macros_exact(original_token.clone())
169        .into_iter()
170        .filter_map(|token| {
171            IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops).map(|it| {
172                it.into_iter().flat_map(|def| def_to_moniker(sema.db, def, current_crate))
173            })
174        })
175        .flatten()
176        .unique()
177        .collect::<Vec<_>>();
178    Some(RangeInfo::new(original_token.text_range(), navs))
179}
180
181pub(crate) fn def_to_kind(db: &RootDatabase, def: Definition) -> SymbolInformationKind {
182    use SymbolInformationKind::*;
183
184    match def {
185        Definition::Macro(it) => match it.kind(db) {
186            MacroKind::Derive
187            | MacroKind::DeriveBuiltIn
188            | MacroKind::AttrBuiltIn
189            | MacroKind::Attr => Attribute,
190            MacroKind::Declarative | MacroKind::DeclarativeBuiltIn | MacroKind::ProcMacro => Macro,
191        },
192        Definition::Field(..) | Definition::TupleField(..) => Field,
193        Definition::Module(..) | Definition::Crate(..) => Module,
194        Definition::Function(it) => {
195            if it.as_assoc_item(db).is_some() {
196                if it.has_self_param(db) {
197                    if it.has_body(db) { Method } else { TraitMethod }
198                } else {
199                    StaticMethod
200                }
201            } else {
202                Function
203            }
204        }
205        Definition::Adt(Adt::Struct(..)) => Struct,
206        Definition::Adt(Adt::Union(..)) => Union,
207        Definition::Adt(Adt::Enum(..)) => Enum,
208        Definition::Variant(..) => EnumMember,
209        Definition::Const(..) => Constant,
210        Definition::Static(..) => StaticVariable,
211        Definition::Trait(..) => Trait,
212        Definition::TypeAlias(it) => {
213            if it.as_assoc_item(db).is_some() {
214                AssociatedType
215            } else {
216                TypeAlias
217            }
218        }
219        Definition::BuiltinType(..) => Type,
220        Definition::BuiltinLifetime(_) => TypeParameter,
221        Definition::SelfType(..) => TypeAlias,
222        Definition::GenericParam(..) => TypeParameter,
223        Definition::Local(it) => {
224            if it.is_self(db) {
225                SelfParameter
226            } else if it.is_param(db) {
227                Parameter
228            } else {
229                Variable
230            }
231        }
232        Definition::Label(..) | Definition::InlineAsmOperand(_) => Variable, // For lack of a better variant
233        Definition::DeriveHelper(..) => Attribute,
234        Definition::BuiltinAttr(..) => Attribute,
235        Definition::ToolModule(..) => Module,
236        Definition::ExternCrateDecl(..) => Module,
237        Definition::InlineAsmRegOrRegClass(..) => Module,
238    }
239}
240
241/// Computes a `MonikerResult` for a definition. Result cases:
242///
243/// * `Some(MonikerResult::Moniker(_))` provides a unique `Moniker` which refers to a definition.
244///
245/// * `Some(MonikerResult::Local { .. })` provides a `Moniker` for the definition enclosing a local.
246///
247/// * `None` is returned for definitions which are not in a module: `BuiltinAttr`, `BuiltinType`,
248///   `BuiltinLifetime`, `TupleField`, `ToolModule`, and `InlineAsmRegOrRegClass`. TODO: it might be
249///   sensible to provide monikers that refer to some non-existent crate of compiler builtin
250///   definitions.
251pub(crate) fn def_to_moniker(
252    db: &RootDatabase,
253    definition: Definition,
254    from_crate: Crate,
255) -> Option<MonikerResult> {
256    match definition {
257        Definition::Local(_) | Definition::Label(_) | Definition::GenericParam(_) => {
258            return Some(MonikerResult::Local {
259                enclosing_moniker: enclosing_def_to_moniker(db, definition, from_crate),
260            });
261        }
262        _ => {}
263    }
264    Some(MonikerResult::Moniker(def_to_non_local_moniker(db, definition, from_crate)?))
265}
266
267fn enclosing_def_to_moniker(
268    db: &RootDatabase,
269    mut def: Definition,
270    from_crate: Crate,
271) -> Option<Moniker> {
272    loop {
273        let enclosing_def = def.enclosing_definition(db)?;
274        if let Some(enclosing_moniker) = def_to_non_local_moniker(db, enclosing_def, from_crate) {
275            return Some(enclosing_moniker);
276        }
277        def = enclosing_def;
278    }
279}
280
281fn def_to_non_local_moniker(
282    db: &RootDatabase,
283    definition: Definition,
284    from_crate: Crate,
285) -> Option<Moniker> {
286    let module = match definition {
287        Definition::Module(module) if module.is_crate_root() => module,
288        _ => definition.module(db)?,
289    };
290    let krate = module.krate();
291    let edition = krate.edition(db);
292
293    // Add descriptors for this definition and every enclosing definition.
294    let mut reverse_description = vec![];
295    let mut def = definition;
296    loop {
297        match def {
298            Definition::SelfType(impl_) => {
299                if let Some(trait_ref) = impl_.trait_ref(db) {
300                    // Trait impls use the trait type for the 2nd parameter.
301                    reverse_description.push(MonikerDescriptor {
302                        name: display(db, module, trait_ref),
303                        desc: MonikerDescriptorKind::TypeParameter,
304                    });
305                }
306                // Both inherent and trait impls use the self type for the first parameter.
307                reverse_description.push(MonikerDescriptor {
308                    name: display(db, module, impl_.self_ty(db)),
309                    desc: MonikerDescriptorKind::TypeParameter,
310                });
311                reverse_description.push(MonikerDescriptor {
312                    name: "impl".to_owned(),
313                    desc: MonikerDescriptorKind::Type,
314                });
315            }
316            _ => {
317                if let Some(name) = def.name(db) {
318                    reverse_description.push(MonikerDescriptor {
319                        name: name.display(db, edition).to_string(),
320                        desc: def_to_kind(db, def).into(),
321                    });
322                } else {
323                    match def {
324                        Definition::Module(module) if module.is_crate_root() => {
325                            // only include `crate` namespace by itself because we prefer
326                            // `rust-analyzer cargo foo . bar/` over `rust-analyzer cargo foo . crate/bar/`
327                            if reverse_description.is_empty() {
328                                reverse_description.push(MonikerDescriptor {
329                                    name: "crate".to_owned(),
330                                    desc: MonikerDescriptorKind::Namespace,
331                                });
332                            }
333                        }
334                        _ => {
335                            tracing::error!(?def, "Encountered enclosing definition with no name");
336                        }
337                    }
338                }
339            }
340        }
341        let Some(next_def) = def.enclosing_definition(db) else {
342            break;
343        };
344        def = next_def;
345    }
346    if reverse_description.is_empty() {
347        return None;
348    }
349    reverse_description.reverse();
350    let description = reverse_description;
351
352    Some(Moniker {
353        identifier: MonikerIdentifier {
354            crate_name: krate.display_name(db)?.crate_name().to_string(),
355            description,
356        },
357        kind: if krate == from_crate { MonikerKind::Export } else { MonikerKind::Import },
358        package_information: {
359            let (name, repo, version) = match krate.origin(db) {
360                CrateOrigin::Library { repo, name } => (name, repo, krate.version(db)),
361                CrateOrigin::Local { repo, name } => (
362                    name.unwrap_or(krate.display_name(db)?.canonical_name().to_owned()),
363                    repo,
364                    krate.version(db),
365                ),
366                CrateOrigin::Rustc { name } => (
367                    name.clone(),
368                    Some("https://github.com/rust-lang/rust/".to_owned()),
369                    Some(format!("https://github.com/rust-lang/rust/compiler/{name}",)),
370                ),
371                CrateOrigin::Lang(lang) => (
372                    krate.display_name(db)?.canonical_name().to_owned(),
373                    Some("https://github.com/rust-lang/rust/".to_owned()),
374                    Some(match lang {
375                        LangCrateOrigin::Other => {
376                            "https://github.com/rust-lang/rust/library/".into()
377                        }
378                        lang => format!("https://github.com/rust-lang/rust/library/{lang}",),
379                    }),
380                ),
381            };
382            PackageInformation { name: name.as_str().to_owned(), repo, version }
383        },
384    })
385}
386
387fn display<T: HirDisplay>(db: &RootDatabase, module: hir::Module, it: T) -> String {
388    match it.display_source_code(db, module.into(), true) {
389        Ok(result) => result,
390        // Fallback on display variant that always succeeds
391        Err(_) => {
392            let fallback_result = it.display(db, module.krate().to_display_target(db)).to_string();
393            tracing::error!(
394                display = %fallback_result, "`display_source_code` failed; falling back to using display"
395            );
396            fallback_result
397        }
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use crate::{MonikerResult, fixture};
404
405    use super::MonikerKind;
406
407    #[allow(dead_code)]
408    #[track_caller]
409    fn no_moniker(#[rust_analyzer::rust_fixture] ra_fixture: &str) {
410        let (analysis, position) = fixture::position(ra_fixture);
411        if let Some(x) = analysis.moniker(position).unwrap() {
412            assert_eq!(x.info.len(), 0, "Moniker found but no moniker expected: {x:?}");
413        }
414    }
415
416    #[track_caller]
417    fn check_local_moniker(
418        #[rust_analyzer::rust_fixture] ra_fixture: &str,
419        identifier: &str,
420        package: &str,
421        kind: MonikerKind,
422    ) {
423        let (analysis, position) = fixture::position(ra_fixture);
424        let x = analysis.moniker(position).unwrap().expect("no moniker found").info;
425        assert_eq!(x.len(), 1);
426        match x.into_iter().next().unwrap() {
427            MonikerResult::Local { enclosing_moniker: Some(x) } => {
428                assert_eq!(identifier, x.identifier.to_string());
429                assert_eq!(package, format!("{:?}", x.package_information));
430                assert_eq!(kind, x.kind);
431            }
432            MonikerResult::Local { enclosing_moniker: None } => {
433                panic!("Unexpected local with no enclosing moniker");
434            }
435            MonikerResult::Moniker(_) => {
436                panic!("Unexpected non-local moniker");
437            }
438        }
439    }
440
441    #[track_caller]
442    fn check_moniker(
443        #[rust_analyzer::rust_fixture] ra_fixture: &str,
444        identifier: &str,
445        package: &str,
446        kind: MonikerKind,
447    ) {
448        let (analysis, position) = fixture::position(ra_fixture);
449        let x = analysis.moniker(position).unwrap().expect("no moniker found").info;
450        assert_eq!(x.len(), 1);
451        match x.into_iter().next().unwrap() {
452            MonikerResult::Local { enclosing_moniker } => {
453                panic!("Unexpected local enclosed in {enclosing_moniker:?}");
454            }
455            MonikerResult::Moniker(x) => {
456                assert_eq!(identifier, x.identifier.to_string());
457                assert_eq!(package, format!("{:?}", x.package_information));
458                assert_eq!(kind, x.kind);
459            }
460        }
461    }
462
463    #[test]
464    fn basic() {
465        check_moniker(
466            r#"
467//- /lib.rs crate:main deps:foo
468use foo::module::func;
469fn main() {
470    func$0();
471}
472//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
473pub mod module {
474    pub fn func() {}
475}
476"#,
477            "foo::module::func",
478            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
479            MonikerKind::Import,
480        );
481        check_moniker(
482            r#"
483//- /lib.rs crate:main deps:foo
484use foo::module::func;
485fn main() {
486    func();
487}
488//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
489pub mod module {
490    pub fn func$0() {}
491}
492"#,
493            "foo::module::func",
494            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
495            MonikerKind::Export,
496        );
497    }
498
499    #[test]
500    fn moniker_for_trait() {
501        check_moniker(
502            r#"
503//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
504pub mod module {
505    pub trait MyTrait {
506        pub fn func$0() {}
507    }
508}
509"#,
510            "foo::module::MyTrait::func",
511            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
512            MonikerKind::Export,
513        );
514    }
515
516    #[test]
517    fn moniker_for_trait_constant() {
518        check_moniker(
519            r#"
520//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
521pub mod module {
522    pub trait MyTrait {
523        const MY_CONST$0: u8;
524    }
525}
526"#,
527            "foo::module::MyTrait::MY_CONST",
528            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
529            MonikerKind::Export,
530        );
531    }
532
533    #[test]
534    fn moniker_for_trait_type() {
535        check_moniker(
536            r#"
537//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
538pub mod module {
539    pub trait MyTrait {
540        type MyType$0;
541    }
542}
543"#,
544            "foo::module::MyTrait::MyType",
545            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
546            MonikerKind::Export,
547        );
548    }
549
550    #[test]
551    fn moniker_for_trait_impl_function() {
552        check_moniker(
553            r#"
554//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
555pub mod module {
556    pub trait MyTrait {
557        pub fn func() {}
558    }
559    struct MyStruct {}
560    impl MyTrait for MyStruct {
561        pub fn func$0() {}
562    }
563}
564"#,
565            "foo::module::impl::MyStruct::MyTrait::func",
566            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
567            MonikerKind::Export,
568        );
569    }
570
571    #[test]
572    fn moniker_for_field() {
573        check_moniker(
574            r#"
575//- /lib.rs crate:main deps:foo
576use foo::St;
577fn main() {
578    let x = St { a$0: 2 };
579}
580//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
581pub struct St {
582    pub a: i32,
583}
584"#,
585            "foo::St::a",
586            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
587            MonikerKind::Import,
588        );
589    }
590
591    #[test]
592    fn local() {
593        check_local_moniker(
594            r#"
595//- /lib.rs crate:main deps:foo
596use foo::module::func;
597fn main() {
598    func();
599}
600//- /foo/lib.rs crate:foo@0.1.0,https://a.b/foo.git library
601pub mod module {
602    pub fn func() {
603        let x$0 = 2;
604    }
605}
606"#,
607            "foo::module::func",
608            r#"PackageInformation { name: "foo", repo: Some("https://a.b/foo.git"), version: Some("0.1.0") }"#,
609            MonikerKind::Export,
610        );
611    }
612}