Skip to content

Commit faf8af0

Browse files
committed
Add command to report unresolved references
1 parent 9b72445 commit faf8af0

File tree

4 files changed

+209
-0
lines changed

4 files changed

+209
-0
lines changed

crates/rust-analyzer/src/bin/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ fn actual_main() -> anyhow::Result<ExitCode> {
8282
flags::RustAnalyzerCmd::Highlight(cmd) => cmd.run()?,
8383
flags::RustAnalyzerCmd::AnalysisStats(cmd) => cmd.run(verbosity)?,
8484
flags::RustAnalyzerCmd::Diagnostics(cmd) => cmd.run()?,
85+
flags::RustAnalyzerCmd::UnresolvedReferences(cmd) => cmd.run()?,
8586
flags::RustAnalyzerCmd::Ssr(cmd) => cmd.run()?,
8687
flags::RustAnalyzerCmd::Search(cmd) => cmd.run()?,
8788
flags::RustAnalyzerCmd::Lsif(cmd) => cmd.run()?,

crates/rust-analyzer/src/cli.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ mod rustc_tests;
1313
mod scip;
1414
mod ssr;
1515
mod symbols;
16+
mod unresolved_references;
1617

1718
mod progress_report;
1819

crates/rust-analyzer/src/cli/flags.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,19 @@ xflags::xflags! {
124124
optional --proc-macro-srv path: PathBuf
125125
}
126126

127+
/// Report unresolved references
128+
cmd unresolved-references {
129+
/// Directory with Cargo.toml.
130+
required path: PathBuf
131+
132+
/// Don't run build scripts or load `OUT_DIR` values by running `cargo check` before analysis.
133+
optional --disable-build-scripts
134+
/// Don't use expand proc macros.
135+
optional --disable-proc-macros
136+
/// Run a custom proc-macro-srv binary.
137+
optional --proc-macro-srv path: PathBuf
138+
}
139+
127140
cmd ssr {
128141
/// A structured search replace rule (`$a.foo($b) ==>> bar($a, $b)`)
129142
repeated rule: SsrRule
@@ -181,6 +194,7 @@ pub enum RustAnalyzerCmd {
181194
RunTests(RunTests),
182195
RustcTests(RustcTests),
183196
Diagnostics(Diagnostics),
197+
UnresolvedReferences(UnresolvedReferences),
184198
Ssr(Ssr),
185199
Search(Search),
186200
Lsif(Lsif),
@@ -250,6 +264,15 @@ pub struct Diagnostics {
250264
pub proc_macro_srv: Option<PathBuf>,
251265
}
252266

267+
#[derive(Debug)]
268+
pub struct UnresolvedReferences {
269+
pub path: PathBuf,
270+
271+
pub disable_build_scripts: bool,
272+
pub disable_proc_macros: bool,
273+
pub proc_macro_srv: Option<PathBuf>,
274+
}
275+
253276
#[derive(Debug)]
254277
pub struct Ssr {
255278
pub rule: Vec<SsrRule>,
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
use hir::{
2+
db::HirDatabase, AnyDiagnostic, Crate, HirFileIdExt as _, MacroFileIdExt as _, Module,
3+
Semantics,
4+
};
5+
use ide::{AnalysisHost, RootDatabase, TextRange};
6+
use ide_db::{
7+
base_db::{SourceDatabase, SourceRootDatabase},
8+
defs::NameRefClass,
9+
EditionedFileId, FxHashSet, LineIndexDatabase as _,
10+
};
11+
use load_cargo::{load_workspace_at, LoadCargoConfig, ProcMacroServerChoice};
12+
use parser::SyntaxKind;
13+
use project_model::{CargoConfig, RustLibSource};
14+
use syntax::{ast, AstNode, WalkEvent};
15+
use vfs::FileId;
16+
17+
use crate::cli::flags;
18+
19+
impl flags::UnresolvedReferences {
20+
pub fn run(self) -> anyhow::Result<()> {
21+
const STACK_SIZE: usize = 1024 * 1024 * 8;
22+
23+
let handle = stdx::thread::Builder::new(stdx::thread::ThreadIntent::LatencySensitive)
24+
.name("BIG_STACK_THREAD".into())
25+
.stack_size(STACK_SIZE)
26+
.spawn(|| self.run_())
27+
.unwrap();
28+
29+
handle.join()
30+
}
31+
fn run_(self) -> anyhow::Result<()> {
32+
let cargo_config =
33+
CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() };
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+
};
45+
let (db, vfs, _proc_macro) =
46+
load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
47+
let host = AnalysisHost::with_database(db);
48+
let db = host.raw_database();
49+
50+
let mut visited_files = FxHashSet::default();
51+
52+
let work = all_modules(db).into_iter().filter(|module| {
53+
let file_id = module.definition_source_file_id(db).original_file(db);
54+
let source_root = db.file_source_root(file_id.into());
55+
let source_root = db.source_root(source_root);
56+
!source_root.is_library
57+
});
58+
59+
for module in work {
60+
let file_id = module.definition_source_file_id(db).original_file(db);
61+
if !visited_files.contains(&file_id) {
62+
let crate_name =
63+
module.krate().display_name(db).as_deref().unwrap_or("unknown").to_owned();
64+
let file_path = vfs.file_path(file_id.into());
65+
eprintln!("processing crate: {crate_name}, module: {file_path}",);
66+
67+
let line_index = db.line_index(file_id.into());
68+
let file_text = db.file_text(file_id.into());
69+
70+
for range in find_unresolved_references(&db, file_id.into(), &module) {
71+
let line_col = line_index.line_col(range.start());
72+
let line = line_col.line + 1;
73+
let col = line_col.col + 1;
74+
let text = &file_text[range];
75+
println!("{file_path}:{line}:{col}: {text}");
76+
}
77+
78+
visited_files.insert(file_id);
79+
}
80+
}
81+
82+
eprintln!();
83+
eprintln!("scan complete");
84+
85+
Ok(())
86+
}
87+
}
88+
89+
fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
90+
let mut worklist: Vec<_> =
91+
Crate::all(db).into_iter().map(|krate| krate.root_module()).collect();
92+
let mut modules = Vec::new();
93+
94+
while let Some(module) = worklist.pop() {
95+
modules.push(module);
96+
worklist.extend(module.children(db));
97+
}
98+
99+
modules
100+
}
101+
102+
fn find_unresolved_references(
103+
db: &RootDatabase,
104+
file_id: FileId,
105+
module: &Module,
106+
) -> Vec<TextRange> {
107+
let mut unresolved_references = all_unresolved_references(db, file_id);
108+
109+
// remove unresolved references which are within inactive code
110+
let mut diagnostics = Vec::new();
111+
module.diagnostics(db, &mut diagnostics, false);
112+
for diagnostic in diagnostics {
113+
let AnyDiagnostic::InactiveCode(inactive_code) = diagnostic else {
114+
continue;
115+
};
116+
117+
let node = inactive_code.node;
118+
119+
if node.file_id != file_id {
120+
continue;
121+
}
122+
123+
unresolved_references.retain(|range| !node.value.text_range().contains_range(*range));
124+
}
125+
126+
unresolved_references
127+
}
128+
129+
fn all_unresolved_references(db: &RootDatabase, file_id: FileId) -> Vec<TextRange> {
130+
let sema = Semantics::new(db);
131+
let file_id = sema
132+
.attach_first_edition(file_id)
133+
.unwrap_or_else(|| EditionedFileId::current_edition(file_id));
134+
let file = sema.parse(file_id);
135+
let root = file.syntax();
136+
137+
let mut unresolved_references = Vec::new();
138+
for event in root.preorder() {
139+
let WalkEvent::Enter(syntax) = event else {
140+
continue;
141+
};
142+
let Some(ast::NameLike::NameRef(name_ref)) = ast::NameLike::cast(syntax) else {
143+
continue;
144+
};
145+
146+
// if we can classify the name_ref, it's not unresolved
147+
if NameRefClass::classify(&sema, &name_ref).is_some() {
148+
continue;
149+
}
150+
151+
// if we couldn't classify it, try descending into macros and classifying that
152+
let Some(ast::NameLike::NameRef(descended_name_ref)) = name_ref
153+
.Self_token()
154+
.or_else(|| name_ref.crate_token())
155+
.or_else(|| name_ref.ident_token())
156+
.or_else(|| name_ref.int_number_token())
157+
.or_else(|| name_ref.self_token())
158+
.or_else(|| name_ref.super_token())
159+
.and_then(|token| {
160+
sema.descend_into_macros_single_exact(token).parent().and_then(ast::NameLike::cast)
161+
})
162+
else {
163+
continue;
164+
};
165+
166+
if NameRefClass::classify(&sema, &descended_name_ref).is_some() {
167+
continue;
168+
}
169+
170+
// if we still couldn't classify it, check if it's TODO
171+
if descended_name_ref.syntax().ancestors().any(|it| it.kind() == SyntaxKind::ATTR)
172+
&& !sema
173+
.hir_file_for(descended_name_ref.syntax())
174+
.macro_file()
175+
.map_or(false, |it| it.is_derive_attr_pseudo_expansion(sema.db))
176+
{
177+
continue;
178+
}
179+
180+
// otherwise, it's unresolved
181+
unresolved_references.push(name_ref.syntax().text_range());
182+
}
183+
unresolved_references
184+
}

0 commit comments

Comments
 (0)