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