Skip to content

Commit 18707cc

Browse files
committed
Add command to report unresolved references
1 parent b032e38 commit 18707cc

File tree

4 files changed

+197
-0
lines changed

4 files changed

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

0 commit comments

Comments
 (0)