Unnamed repository; edit this file 'description' to name the repository.
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
import * as vscode from "vscode";
import * as lc from "vscode-languageclient/node";

import * as commands from "./commands";
import { type CommandFactory, Ctx, fetchWorkspace } from "./ctx";
import * as diagnostics from "./diagnostics";
import { activateTaskProvider } from "./tasks";
import { setContextValue } from "./util";
import { initializeDebugSessionTrackingAndRebuild } from "./debug";

const RUST_PROJECT_CONTEXT_NAME = "inRustProject";

export interface RustAnalyzerExtensionApi {
    // FIXME: this should be non-optional
    readonly client?: lc.LanguageClient;
}

export async function deactivate() {
    await setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined);
}

export async function activate(
    context: vscode.ExtensionContext,
): Promise<RustAnalyzerExtensionApi> {
    checkConflictingExtensions();

    const ctx = new Ctx(context, createCommands(), fetchWorkspace());
    // VS Code doesn't show a notification when an extension fails to activate
    // so we do it ourselves.
    const api = await activateServer(ctx).catch((err) => {
        void vscode.window.showErrorMessage(
            `Cannot activate rust-analyzer extension: ${err.message}`,
        );
        throw err;
    });
    await setContextValue(RUST_PROJECT_CONTEXT_NAME, true);
    return api;
}

async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
    if (ctx.workspace.kind === "Workspace Folder") {
        ctx.pushExtCleanup(activateTaskProvider(ctx.config));
    }

    const diagnosticProvider = new diagnostics.TextDocumentProvider(ctx);
    ctx.pushExtCleanup(
        vscode.workspace.registerTextDocumentContentProvider(
            diagnostics.URI_SCHEME,
            diagnosticProvider,
        ),
    );

    const decorationProvider = new diagnostics.AnsiDecorationProvider(ctx);
    ctx.pushExtCleanup(decorationProvider);

    async function decorateVisibleEditors(document: vscode.TextDocument) {
        for (const editor of vscode.window.visibleTextEditors) {
            if (document === editor.document) {
                await decorationProvider.provideDecorations(editor);
            }
        }
    }

    vscode.workspace.onDidChangeTextDocument(
        async (event) => await decorateVisibleEditors(event.document),
        null,
        ctx.subscriptions,
    );
    vscode.workspace.onDidOpenTextDocument(decorateVisibleEditors, null, ctx.subscriptions);
    vscode.window.onDidChangeActiveTextEditor(
        async (editor) => {
            if (editor) {
                diagnosticProvider.triggerUpdate(editor.document.uri);
                await decorateVisibleEditors(editor.document);
            }
        },
        null,
        ctx.subscriptions,
    );
    vscode.window.onDidChangeVisibleTextEditors(
        async (visibleEditors) => {
            for (const editor of visibleEditors) {
                diagnosticProvider.triggerUpdate(editor.document.uri);
                await decorationProvider.provideDecorations(editor);
            }
        },
        null,
        ctx.subscriptions,
    );

    vscode.workspace.onDidChangeWorkspaceFolders(
        async (_) => ctx.onWorkspaceFolderChanges(),
        null,
        ctx.subscriptions,
    );
    vscode.workspace.onDidChangeConfiguration(
        async (_) => {
            await ctx.client?.sendNotification(lc.DidChangeConfigurationNotification.type, {
                settings: "",
            });
        },
        null,
        ctx.subscriptions,
    );

    if (ctx.config.debug.buildBeforeRestart) {
        initializeDebugSessionTrackingAndRebuild(ctx);
    }

    if (ctx.config.initializeStopped) {
        ctx.setServerStatus({
            health: "stopped",
        });
    } else {
        await ctx.start();
    }

    return ctx;
}

function createCommands(): Record<string, CommandFactory> {
    return {
        onEnter: {
            enabled: commands.onEnter,
            disabled: (_) => () => vscode.commands.executeCommand("default:type", { text: "\n" }),
        },
        restartServer: {
            enabled: (ctx) => async () => {
                await ctx.restart();
            },
            disabled: (ctx) => async () => {
                await ctx.start();
            },
        },
        startServer: {
            enabled: (ctx) => async () => {
                await ctx.start();
            },
            disabled: (ctx) => async () => {
                await ctx.start();
            },
        },
        stopServer: {
            enabled: (ctx) => async () => {
                // FIXME: We should re-use the client, that is ctx.deactivate() if none of the configs have changed
                await ctx.stopAndDispose();
                ctx.setServerStatus({
                    health: "stopped",
                });
            },
            disabled: (_) => async () => {},
        },

        analyzerStatus: { enabled: commands.analyzerStatus },
        memoryUsage: { enabled: commands.memoryUsage },
        reloadWorkspace: { enabled: commands.reloadWorkspace },
        rebuildProcMacros: { enabled: commands.rebuildProcMacros },
        matchingBrace: { enabled: commands.matchingBrace },
        joinLines: { enabled: commands.joinLines },
        parentModule: { enabled: commands.parentModule },
        childModules: { enabled: commands.childModules },
        viewHir: { enabled: commands.viewHir },
        viewMir: { enabled: commands.viewMir },
        interpretFunction: { enabled: commands.interpretFunction },
        viewFileText: { enabled: commands.viewFileText },
        viewItemTree: { enabled: commands.viewItemTree },
        viewCrateGraph: { enabled: commands.viewCrateGraph },
        viewFullCrateGraph: { enabled: commands.viewFullCrateGraph },
        expandMacro: { enabled: commands.expandMacro },
        run: { enabled: commands.run },
        copyRunCommandLine: { enabled: commands.copyRunCommandLine },
        debug: { enabled: commands.debug },
        newDebugConfig: { enabled: commands.newDebugConfig },
        openDocs: { enabled: commands.openDocs },
        openExternalDocs: { enabled: commands.openExternalDocs },
        openCargoToml: { enabled: commands.openCargoToml },
        peekTests: { enabled: commands.peekTests },
        moveItemUp: { enabled: commands.moveItemUp },
        moveItemDown: { enabled: commands.moveItemDown },
        cancelFlycheck: { enabled: commands.cancelFlycheck },
        clearFlycheck: { enabled: commands.clearFlycheck },
        runFlycheck: { enabled: commands.runFlycheck },
        ssr: { enabled: commands.ssr },
        serverVersion: { enabled: commands.serverVersion },
        viewMemoryLayout: { enabled: commands.viewMemoryLayout },
        toggleCheckOnSave: { enabled: commands.toggleCheckOnSave },
        toggleLSPLogs: { enabled: commands.toggleLSPLogs },
        openWalkthrough: { enabled: commands.openWalkthrough },
        // Internal commands which are invoked by the server.
        applyActionGroup: { enabled: commands.applyActionGroup },
        applySnippetWorkspaceEdit: {
            enabled: commands.applySnippetWorkspaceEditCommand,
        },
        debugSingle: { enabled: commands.debugSingle },
        gotoLocation: { enabled: commands.gotoLocation },
        hoverRefCommandProxy: { enabled: commands.hoverRefCommandProxy },
        resolveCodeAction: { enabled: commands.resolveCodeAction },
        runSingle: { enabled: commands.runSingle },
        showReferences: { enabled: commands.showReferences },
        triggerParameterHints: { enabled: commands.triggerParameterHints },
        rename: { enabled: commands.rename },
        openLogs: { enabled: commands.openLogs },
        revealDependency: { enabled: commands.revealDependency },
        syntaxTreeReveal: { enabled: commands.syntaxTreeReveal },
        syntaxTreeCopy: { enabled: commands.syntaxTreeCopy },
        syntaxTreeHideWhitespace: {
            enabled: commands.syntaxTreeHideWhitespace,
        },
        syntaxTreeShowWhitespace: {
            enabled: commands.syntaxTreeShowWhitespace,
        },
    };
}

function checkConflictingExtensions() {
    if (vscode.extensions.getExtension("rust-lang.rust")) {
        vscode.window
            .showWarningMessage(
                `You have both the rust-analyzer (rust-lang.rust-analyzer) and Rust (rust-lang.rust) ` +
                    "plugins enabled. These are known to conflict and cause various functions of " +
                    "both plugins to not work correctly. You should disable one of them.",
                "Got it",
            )
            // eslint-disable-next-line no-console
            .then(() => {}, console.error);
    }
}
29 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
use hir::{HasSource, InFile, InRealFile, Semantics};
use ide_db::{
    FileId, FilePosition, FileRange, FxIndexSet, RootDatabase, defs::Definition,
    helpers::visit_file_defs, ra_fixture::RaFixtureConfig,
};
use itertools::Itertools;
use syntax::{AstNode, TextRange, ast::HasName};

use crate::{
    NavigationTarget, RunnableKind,
    annotations::fn_references::find_all_methods,
    goto_implementation::{GotoImplementationConfig, goto_implementation},
    navigation_target,
    references::{FindAllRefsConfig, find_all_refs},
    runnables::{Runnable, runnables},
};

mod fn_references;

// Feature: Annotations
//
// Provides user with annotations above items for looking up references or impl blocks
// and running/debugging binaries.
//
// ![Annotations](https://user-images.githubusercontent.com/48062697/113020672-b7c34f00-917a-11eb-8f6e-858735660a0e.png)
#[derive(Debug, Hash, PartialEq, Eq)]
pub struct Annotation {
    pub range: TextRange,
    pub kind: AnnotationKind,
}

#[derive(Debug, Hash, PartialEq, Eq)]
pub enum AnnotationKind {
    Runnable(Runnable),
    HasImpls { pos: FilePosition, data: Option<Vec<NavigationTarget>> },
    HasReferences { pos: FilePosition, data: Option<Vec<FileRange>> },
}

pub struct AnnotationConfig<'a> {
    pub binary_target: bool,
    pub annotate_runnables: bool,
    pub annotate_impls: bool,
    pub annotate_references: bool,
    pub annotate_method_references: bool,
    pub annotate_enum_variant_references: bool,
    pub location: AnnotationLocation,
    pub filter_adjacent_derive_implementations: bool,
    pub ra_fixture: RaFixtureConfig<'a>,
}

pub enum AnnotationLocation {
    AboveName,
    AboveWholeItem,
}

pub(crate) fn annotations(
    db: &RootDatabase,
    config: &AnnotationConfig<'_>,
    file_id: FileId,
) -> Vec<Annotation> {
    let mut annotations = FxIndexSet::default();

    if config.annotate_runnables {
        for runnable in runnables(db, file_id) {
            if should_skip_runnable(&runnable.kind, config.binary_target) {
                continue;
            }

            let range = runnable.nav.focus_or_full_range();

            annotations.insert(Annotation { range, kind: AnnotationKind::Runnable(runnable) });
        }
    }

    let mk_ranges = |(range, focus): (_, Option<_>)| {
        let cmd_target: TextRange = focus.unwrap_or(range);
        let annotation_range = match config.location {
            AnnotationLocation::AboveName => cmd_target,
            AnnotationLocation::AboveWholeItem => range,
        };
        let target_pos = FilePosition { file_id, offset: cmd_target.start() };
        (annotation_range, target_pos)
    };

    visit_file_defs(&Semantics::new(db), file_id, &mut |def| {
        let range = match def {
            Definition::Const(konst) if config.annotate_references => {
                konst.source(db).and_then(|node| name_range(db, node, file_id))
            }
            Definition::Trait(trait_) if config.annotate_references || config.annotate_impls => {
                trait_.source(db).and_then(|node| name_range(db, node, file_id))
            }
            Definition::Adt(adt) => match adt {
                hir::Adt::Enum(enum_) => {
                    if config.annotate_enum_variant_references {
                        enum_
                            .variants(db)
                            .into_iter()
                            .filter_map(|variant| {
                                variant.source(db).and_then(|node| name_range(db, node, file_id))
                            })
                            .for_each(|range| {
                                let (annotation_range, target_position) = mk_ranges(range);
                                annotations.insert(Annotation {
                                    range: annotation_range,
                                    kind: AnnotationKind::HasReferences {
                                        pos: target_position,
                                        data: None,
                                    },
                                });
                            })
                    }
                    if config.annotate_references || config.annotate_impls {
                        enum_.source(db).and_then(|node| name_range(db, node, file_id))
                    } else {
                        None
                    }
                }
                _ => {
                    if config.annotate_references || config.annotate_impls {
                        adt.source(db).and_then(|node| name_range(db, node, file_id))
                    } else {
                        None
                    }
                }
            },
            _ => None,
        };

        let range = match range {
            Some(range) => range,
            None => return,
        };
        let (annotation_range, target_pos) = mk_ranges(range);
        if config.annotate_impls && !matches!(def, Definition::Const(_)) {
            annotations.insert(Annotation {
                range: annotation_range,
                kind: AnnotationKind::HasImpls { pos: target_pos, data: None },
            });
        }

        if config.annotate_references {
            annotations.insert(Annotation {
                range: annotation_range,
                kind: AnnotationKind::HasReferences { pos: target_pos, data: None },
            });
        }

        fn name_range<T: HasName>(
            db: &RootDatabase,
            node: InFile<T>,
            source_file_id: FileId,
        ) -> Option<(TextRange, Option<TextRange>)> {
            if let Some(name) = node.value.name().map(|name| name.syntax().text_range()) {
                // if we have a name, try mapping that out of the macro expansion as we can put the
                // annotation on that name token
                // See `test_no_annotations_macro_struct_def` vs `test_annotations_macro_struct_def_call_site`
                let res = navigation_target::orig_range_with_focus_r(
                    db,
                    node.file_id,
                    node.value.syntax().text_range(),
                    Some(name),
                );
                if res.call_site.0.file_id == source_file_id
                    && let Some(name_range) = res.call_site.1
                {
                    return Some((res.call_site.0.range, Some(name_range)));
                }
            };
            // otherwise try upmapping the entire node out of attributes
            let InRealFile { file_id, value } = node.original_ast_node_rooted(db)?;
            if file_id.file_id(db) == source_file_id {
                Some((
                    value.syntax().text_range(),
                    value.name().map(|name| name.syntax().text_range()),
                ))
            } else {
                None
            }
        }
    });

    if config.annotate_method_references {
        annotations.extend(find_all_methods(db, file_id).into_iter().map(|range| {
            let (annotation_range, target_range) = mk_ranges(range);
            Annotation {
                range: annotation_range,
                kind: AnnotationKind::HasReferences { pos: target_range, data: None },
            }
        }));
    }

    annotations
        .into_iter()
        .sorted_by_key(|a| {
            (a.range.start(), a.range.end(), matches!(a.kind, AnnotationKind::Runnable(..)))
        })
        .collect()
}

pub(crate) fn resolve_annotation(
    db: &RootDatabase,
    config: &AnnotationConfig<'_>,
    mut annotation: Annotation,
) -> Annotation {
    match annotation.kind {
        AnnotationKind::HasImpls { pos, ref mut data } => {
            let goto_implementation_config = GotoImplementationConfig {
                filter_adjacent_derive_implementations: config
                    .filter_adjacent_derive_implementations,
            };
            *data =
                goto_implementation(db, &goto_implementation_config, pos).map(|range| range.info);
        }
        AnnotationKind::HasReferences { pos, ref mut data } => {
            *data = find_all_refs(
                &Semantics::new(db),
                pos,
                &FindAllRefsConfig {
                    search_scope: None,
                    ra_fixture: config.ra_fixture,
                    exclude_imports: false,
                    exclude_tests: false,
                },
            )
            .map(|result| {
                result
                    .into_iter()
                    .flat_map(|res| res.references)
                    .flat_map(|(file_id, access)| {
                        access.into_iter().map(move |(range, _)| FileRange { file_id, range })
                    })
                    .collect()
            });
        }
        _ => {}
    };

    annotation
}

fn should_skip_runnable(kind: &RunnableKind, binary_target: bool) -> bool {
    match kind {
        RunnableKind::Bin => !binary_target,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use expect_test::{Expect, expect};
    use ide_db::ra_fixture::RaFixtureConfig;

    use crate::{Annotation, AnnotationConfig, fixture};

    use super::AnnotationLocation;

    const DEFAULT_CONFIG: AnnotationConfig<'_> = AnnotationConfig {
        binary_target: true,
        annotate_runnables: true,
        annotate_impls: true,
        annotate_references: true,
        annotate_method_references: true,
        annotate_enum_variant_references: true,
        location: AnnotationLocation::AboveName,
        ra_fixture: RaFixtureConfig::default(),
        filter_adjacent_derive_implementations: false,
    };

    fn check_with_config(
        #[rust_analyzer::rust_fixture] ra_fixture: &str,
        expect: Expect,
        config: &AnnotationConfig<'_>,
    ) {
        let (analysis, file_id) = fixture::file(ra_fixture);

        let annotations: Vec<Annotation> = analysis
            .annotations(config, file_id)
            .unwrap()
            .into_iter()
            .map(|annotation| analysis.resolve_annotation(&DEFAULT_CONFIG, annotation).unwrap())
            .collect();

        expect.assert_debug_eq(&annotations);
    }

    fn check(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
        check_with_config(ra_fixture, expect, &DEFAULT_CONFIG);
    }

    #[test]
    fn const_annotations() {
        check(
            r#"
const DEMO: i32 = 123;

const UNUSED: i32 = 123;

fn main() {
    let hello = DEMO;
}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 6..10,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 6,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 78..82,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 30..36,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 30,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 53..57,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 53,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 53..57,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 50..85,
                                    focus_range: 53..57,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn struct_references_annotations() {
        check(
            r#"
struct Test;

fn main() {
    let test = Test;
}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 7..11,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 7..11,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 41..45,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 17..21,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 17,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 17..21,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 14..48,
                                    focus_range: 17..21,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn struct_and_trait_impls_annotations() {
        check(
            r#"
struct Test;

trait MyCoolTrait {}

impl MyCoolTrait for Test {}

fn main() {
    let test = Test;
}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 7..11,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [
                                    NavigationTarget {
                                        file_id: FileId(
                                            0,
                                        ),
                                        full_range: 36..64,
                                        focus_range: 57..61,
                                        name: "impl",
                                        kind: Impl,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 7..11,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 57..61,
                                    },
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 93..97,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 20..31,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 20,
                            },
                            data: Some(
                                [
                                    NavigationTarget {
                                        file_id: FileId(
                                            0,
                                        ),
                                        full_range: 36..64,
                                        focus_range: 57..61,
                                        name: "impl",
                                        kind: Impl,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 20..31,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 20,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 41..52,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 69..73,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 69,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 69..73,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 66..100,
                                    focus_range: 69..73,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn runnable_annotation() {
        check(
            r#"
fn main() {}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 3..7,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 3,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 3..7,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 0..12,
                                    focus_range: 3..7,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn method_annotations() {
        check(
            r#"
struct Test;

impl Test {
    fn self_by_ref(&self) {}
}

fn main() {
    Test.self_by_ref();
}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 7..11,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [
                                    NavigationTarget {
                                        file_id: FileId(
                                            0,
                                        ),
                                        full_range: 14..56,
                                        focus_range: 19..23,
                                        name: "impl",
                                        kind: Impl,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 7..11,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 7,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 19..23,
                                    },
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 74..78,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 33..44,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 33,
                            },
                            data: Some(
                                [
                                    FileRangeWrapper {
                                        file_id: FileId(
                                            0,
                                        ),
                                        range: 79..90,
                                    },
                                ],
                            ),
                        },
                    },
                    Annotation {
                        range: 61..65,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 61,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 61..65,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 58..95,
                                    focus_range: 61..65,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn test_annotations() {
        check(
            r#"
fn main() {}

mod tests {
    #[test]
    fn my_cool_test() {}
}
            "#,
            expect![[r#"
                [
                    Annotation {
                        range: 3..7,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 3,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 3..7,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 0..12,
                                    focus_range: 3..7,
                                    name: "main",
                                    kind: Function,
                                },
                                kind: Bin,
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                    Annotation {
                        range: 18..23,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 14..64,
                                    focus_range: 18..23,
                                    name: "tests",
                                    kind: Module,
                                    description: "mod tests",
                                },
                                kind: TestMod {
                                    path: "tests",
                                },
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                    Annotation {
                        range: 45..57,
                        kind: Runnable(
                            Runnable {
                                use_name_in_title: false,
                                nav: NavigationTarget {
                                    file_id: FileId(
                                        0,
                                    ),
                                    full_range: 30..62,
                                    focus_range: 45..57,
                                    name: "my_cool_test",
                                    kind: Function,
                                },
                                kind: Test {
                                    test_id: Path(
                                        "tests::my_cool_test",
                                    ),
                                },
                                cfg: None,
                                update_test: UpdateTest {
                                    expect_test: false,
                                    insta: false,
                                    snapbox: false,
                                },
                            },
                        ),
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn test_no_annotations_outside_module_tree() {
        check(
            r#"
//- /foo.rs
struct Foo;
//- /lib.rs
// this file comes last since `check` checks the first file only
"#,
            expect![[r#"
                []
            "#]],
        );
    }

    #[test]
    fn test_no_annotations_macro_struct_def() {
        check(
            r#"
//- /lib.rs
macro_rules! m {
    () => {
        struct A {}
    };
}

m!();
"#,
            expect![[r#"
                []
            "#]],
        );
    }

    #[test]
    fn test_annotations_macro_struct_def_call_site() {
        check(
            r#"
//- /lib.rs
macro_rules! m {
    ($name:ident) => {
        struct $name {}
    };
}

m! {
    Name
};
"#,
            expect![[r#"
                [
                    Annotation {
                        range: 83..87,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 83,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 83..87,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 83,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                ]
            "#]],
        );
    }

    #[test]
    fn test_annotations_appear_above_whole_item_when_configured_to_do_so() {
        check_with_config(
            r#"
/// This is a struct named Foo, obviously.
#[derive(Clone)]
struct Foo;
"#,
            expect![[r#"
                [
                    Annotation {
                        range: 0..71,
                        kind: HasImpls {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 67,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                    Annotation {
                        range: 0..71,
                        kind: HasReferences {
                            pos: FilePositionWrapper {
                                file_id: FileId(
                                    0,
                                ),
                                offset: 67,
                            },
                            data: Some(
                                [],
                            ),
                        },
                    },
                ]
            "#]],
            &AnnotationConfig { location: AnnotationLocation::AboveWholeItem, ..DEFAULT_CONFIG },
        );
    }
}