rust_analyzer/cli/
unresolved_references.rs

1//! Reports references in code that the IDE layer cannot resolve.
2use hir::{AnyDiagnostic, Crate, Module, Semantics, db::HirDatabase, sym};
3use ide::{AnalysisHost, RootDatabase, TextRange};
4use ide_db::{
5    EditionedFileId, FxHashSet, LineIndexDatabase as _, base_db::SourceDatabase, defs::NameRefClass,
6};
7use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace_at};
8use parser::SyntaxKind;
9use syntax::{AstNode, WalkEvent, ast};
10use vfs::FileId;
11
12use crate::cli::flags;
13
14impl flags::UnresolvedReferences {
15    pub fn run(self) -> anyhow::Result<()> {
16        const STACK_SIZE: usize = 1024 * 1024 * 8;
17
18        let handle = stdx::thread::Builder::new(
19            stdx::thread::ThreadIntent::LatencySensitive,
20            "BIG_STACK_THREAD",
21        )
22        .stack_size(STACK_SIZE)
23        .spawn(|| self.run_())
24        .unwrap();
25
26        handle.join()
27    }
28
29    fn run_(self) -> anyhow::Result<()> {
30        let root =
31            vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(&self.path)).normalize();
32        let config = crate::config::Config::new(
33            root,
34            lsp_types::ClientCapabilities::default(),
35            vec![],
36            None,
37        );
38        let cargo_config = config.cargo(None);
39        let with_proc_macro_server = if let Some(p) = &self.proc_macro_srv {
40            let path = vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(p));
41            ProcMacroServerChoice::Explicit(path)
42        } else {
43            ProcMacroServerChoice::Sysroot
44        };
45        let load_cargo_config = LoadCargoConfig {
46            load_out_dirs_from_check: !self.disable_build_scripts,
47            with_proc_macro_server,
48            prefill_caches: false,
49        };
50        let (db, vfs, _proc_macro) =
51            load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
52        let host = AnalysisHost::with_database(db);
53        let db = host.raw_database();
54        let sema = Semantics::new(db);
55
56        let mut visited_files = FxHashSet::default();
57
58        let work = all_modules(db).into_iter().filter(|module| {
59            let file_id = module.definition_source_file_id(db).original_file(db);
60            let source_root = db.file_source_root(file_id.file_id(db)).source_root_id(db);
61            let source_root = db.source_root(source_root).source_root(db);
62            !source_root.is_library
63        });
64
65        for module in work {
66            let file_id = module.definition_source_file_id(db).original_file(db);
67            let file_id = file_id.file_id(db);
68            if !visited_files.contains(&file_id) {
69                let crate_name =
70                    module.krate().display_name(db).as_deref().unwrap_or(&sym::unknown).to_owned();
71                let file_path = vfs.file_path(file_id);
72                eprintln!("processing crate: {crate_name}, module: {file_path}",);
73
74                let line_index = db.line_index(file_id);
75                let file_text = db.file_text(file_id);
76
77                for range in find_unresolved_references(db, &sema, file_id, &module) {
78                    let line_col = line_index.line_col(range.start());
79                    let line = line_col.line + 1;
80                    let col = line_col.col + 1;
81                    let text = &file_text.text(db)[range];
82                    println!("{file_path}:{line}:{col}: {text}");
83                }
84
85                visited_files.insert(file_id);
86            }
87        }
88
89        eprintln!();
90        eprintln!("scan complete");
91
92        Ok(())
93    }
94}
95
96fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
97    let mut worklist: Vec<_> =
98        Crate::all(db).into_iter().map(|krate| krate.root_module()).collect();
99    let mut modules = Vec::new();
100
101    while let Some(module) = worklist.pop() {
102        modules.push(module);
103        worklist.extend(module.children(db));
104    }
105
106    modules
107}
108
109fn find_unresolved_references(
110    db: &RootDatabase,
111    sema: &Semantics<'_, RootDatabase>,
112    file_id: FileId,
113    module: &Module,
114) -> Vec<TextRange> {
115    let mut unresolved_references = all_unresolved_references(sema, file_id);
116
117    // remove unresolved references which are within inactive code
118    let mut diagnostics = Vec::new();
119    module.diagnostics(db, &mut diagnostics, false);
120    for diagnostic in diagnostics {
121        let AnyDiagnostic::InactiveCode(inactive_code) = diagnostic else {
122            continue;
123        };
124
125        let node = inactive_code.node;
126        let range = node.map(|it| it.text_range()).original_node_file_range_rooted(db);
127
128        if range.file_id.file_id(db) != file_id {
129            continue;
130        }
131
132        unresolved_references.retain(|r| !range.range.contains_range(*r));
133    }
134
135    unresolved_references
136}
137
138fn all_unresolved_references(
139    sema: &Semantics<'_, RootDatabase>,
140    file_id: FileId,
141) -> Vec<TextRange> {
142    let file_id = sema
143        .attach_first_edition(file_id)
144        .unwrap_or_else(|| EditionedFileId::current_edition(sema.db, file_id));
145    let file = sema.parse(file_id);
146    let root = file.syntax();
147
148    let mut unresolved_references = Vec::new();
149    for event in root.preorder() {
150        let WalkEvent::Enter(syntax) = event else {
151            continue;
152        };
153        let Some(name_ref) = ast::NameRef::cast(syntax) else {
154            continue;
155        };
156        let Some(descended_name_ref) = name_ref.syntax().first_token().and_then(|tok| {
157            sema.descend_into_macros_single_exact(tok).parent().and_then(ast::NameRef::cast)
158        }) else {
159            continue;
160        };
161
162        // if we can classify the name_ref, it's not unresolved
163        if NameRefClass::classify(sema, &descended_name_ref).is_some() {
164            continue;
165        }
166
167        // if we couldn't classify it, but it's in an attr, ignore it. See #10935
168        if descended_name_ref.syntax().ancestors().any(|it| it.kind() == SyntaxKind::ATTR) {
169            continue;
170        }
171
172        // otherwise, it's unresolved
173        unresolved_references.push(name_ref.syntax().text_range());
174    }
175    unresolved_references
176}