rust_analyzer/cli/
unresolved_references.rs1use hir::{AnyDiagnostic, Crate, Module, Semantics, db::HirDatabase, sym};
3use ide::{AnalysisHost, RootDatabase, TextRange};
4use ide_db::{FxHashSet, base_db::SourceDatabase, defs::NameRefClass, line_index};
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 let handle = stdx::thread::Builder::new(
15 stdx::thread::ThreadIntent::LatencySensitive,
16 "BIG_STACK_THREAD",
17 )
18 .spawn(|| self.run_())
19 .unwrap();
20
21 handle.join()
22 }
23
24 fn run_(self) -> anyhow::Result<()> {
25 let root =
26 vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(&self.path)).normalize();
27 let config = crate::config::Config::new(
28 root,
29 lsp_types::ClientCapabilities::default(),
30 vec![],
31 None,
32 );
33 let cargo_config = config.cargo(None);
34 let with_proc_macro_server = if let Some(p) = &self.proc_macro_srv {
35 let path = vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(p));
36 ProcMacroServerChoice::Explicit(path)
37 } else {
38 ProcMacroServerChoice::Sysroot
39 };
40 let load_cargo_config = LoadCargoConfig {
41 load_out_dirs_from_check: !self.disable_build_scripts,
42 with_proc_macro_server,
43 prefill_caches: false,
44 num_worker_threads: 1,
45 proc_macro_processes: config.proc_macro_num_processes(),
46 };
47 let (db, vfs, _proc_macro) =
48 load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
49 let host = AnalysisHost::with_database(db);
50 let db = host.raw_database();
51 let sema = Semantics::new(db);
52
53 let mut visited_files = FxHashSet::default();
54
55 let work = all_modules(db).into_iter().filter(|module| {
56 let file_id = module.definition_source_file_id(db).original_file(db);
57 let source_root = db.file_source_root(file_id.file_id(db)).source_root_id(db);
58 let source_root = db.source_root(source_root).source_root(db);
59 !source_root.is_library
60 });
61
62 hir::attach_db(db, || {
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 = line_index(db, 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
92 eprintln!();
93 eprintln!("scan complete");
94
95 Ok(())
96 }
97}
98
99fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
100 let mut worklist: Vec<_> =
101 Crate::all(db).into_iter().map(|krate| krate.root_module(db)).collect();
102 let mut modules = Vec::new();
103
104 while let Some(module) = worklist.pop() {
105 modules.push(module);
106 worklist.extend(module.children(db));
107 }
108
109 modules
110}
111
112fn find_unresolved_references(
113 db: &RootDatabase,
114 sema: &Semantics<'_, RootDatabase>,
115 file_id: FileId,
116 module: &Module,
117) -> Vec<TextRange> {
118 let mut unresolved_references = all_unresolved_references(sema, file_id);
119
120 let mut diagnostics = Vec::new();
122 module.diagnostics(db, &mut diagnostics, false);
123 for diagnostic in diagnostics {
124 let AnyDiagnostic::InactiveCode(inactive_code) = diagnostic else {
125 continue;
126 };
127
128 let node = inactive_code.node;
129 let range = node.map(|it| it.text_range()).original_node_file_range_rooted(db);
130
131 if range.file_id.file_id(db) != file_id {
132 continue;
133 }
134
135 unresolved_references.retain(|r| !range.range.contains_range(*r));
136 }
137
138 unresolved_references
139}
140
141fn all_unresolved_references(
142 sema: &Semantics<'_, RootDatabase>,
143 file_id: FileId,
144) -> Vec<TextRange> {
145 let file_id = sema.attach_first_edition(file_id);
146 let file = sema.parse(file_id);
147 let root = file.syntax();
148
149 let mut unresolved_references = Vec::new();
150 for event in root.preorder() {
151 let WalkEvent::Enter(syntax) = event else {
152 continue;
153 };
154 let Some(name_ref) = ast::NameRef::cast(syntax) else {
155 continue;
156 };
157 let Some(descended_name_ref) = name_ref.syntax().first_token().and_then(|tok| {
158 sema.descend_into_macros_single_exact(tok).parent().and_then(ast::NameRef::cast)
159 }) else {
160 continue;
161 };
162
163 if NameRefClass::classify(sema, &descended_name_ref).is_some() {
165 continue;
166 }
167
168 if descended_name_ref.syntax().ancestors().any(|it| it.kind() == SyntaxKind::ATTR) {
170 continue;
171 }
172
173 unresolved_references.push(name_ref.syntax().text_range());
175 }
176 unresolved_references
177}