Skip to content

Commit 2bd28c6

Browse files
bors[bot]matklad
andauthored
Merge #9834
9834: internal: unify subcommand handling between ra and xtask r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
2 parents 74470a0 + 9cf5914 commit 2bd28c6

File tree

9 files changed

+201
-206
lines changed

9 files changed

+201
-206
lines changed

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

Lines changed: 9 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,14 @@
11
//! Driver for rust-analyzer.
22
//!
33
//! Based on cli flags, either spawns an LSP server, or runs a batch analysis
4-
mod flags;
54
mod logger;
65
mod rustc_wrapper;
76

87
use std::{convert::TryFrom, env, fs, path::Path, process};
98

109
use lsp_server::Connection;
1110
use project_model::ProjectManifest;
12-
use rust_analyzer::{
13-
cli::{self, AnalysisStatsCmd},
14-
config::Config,
15-
from_json,
16-
lsp_ext::supports_utf8,
17-
Result,
18-
};
11+
use rust_analyzer::{cli::flags, config::Config, from_json, lsp_ext::supports_utf8, Result};
1912
use vfs::AbsPathBuf;
2013

2114
#[cfg(all(feature = "mimalloc"))]
@@ -86,29 +79,14 @@ fn try_main() -> Result<()> {
8679
}
8780
run_server()?
8881
}
89-
flags::RustAnalyzerCmd::ProcMacro(_) => proc_macro_srv::cli::run()?,
90-
flags::RustAnalyzerCmd::Parse(cmd) => cli::parse(cmd.no_dump)?,
91-
flags::RustAnalyzerCmd::Symbols(_) => cli::symbols()?,
92-
flags::RustAnalyzerCmd::Highlight(cmd) => cli::highlight(cmd.rainbow)?,
93-
flags::RustAnalyzerCmd::AnalysisStats(cmd) => AnalysisStatsCmd {
94-
randomize: cmd.randomize,
95-
parallel: cmd.parallel,
96-
memory_usage: cmd.memory_usage,
97-
only: cmd.only,
98-
with_deps: cmd.with_deps,
99-
no_sysroot: cmd.no_sysroot,
100-
path: cmd.path,
101-
enable_build_scripts: !cmd.disable_build_scripts,
102-
enable_proc_macros: !cmd.disable_proc_macros,
103-
skip_inference: cmd.skip_inference,
104-
}
105-
.run(verbosity)?,
106-
107-
flags::RustAnalyzerCmd::Diagnostics(cmd) => {
108-
cli::diagnostics(&cmd.path, !cmd.disable_build_scripts, !cmd.disable_proc_macros)?
109-
}
110-
flags::RustAnalyzerCmd::Ssr(cmd) => cli::apply_ssr_rules(cmd.rule)?,
111-
flags::RustAnalyzerCmd::Search(cmd) => cli::search_for_patterns(cmd.pattern, cmd.debug)?,
82+
flags::RustAnalyzerCmd::ProcMacro(flags::ProcMacro) => proc_macro_srv::cli::run()?,
83+
flags::RustAnalyzerCmd::Parse(cmd) => cmd.run()?,
84+
flags::RustAnalyzerCmd::Symbols(cmd) => cmd.run()?,
85+
flags::RustAnalyzerCmd::Highlight(cmd) => cmd.run()?,
86+
flags::RustAnalyzerCmd::AnalysisStats(cmd) => cmd.run(verbosity)?,
87+
flags::RustAnalyzerCmd::Diagnostics(cmd) => cmd.run()?,
88+
flags::RustAnalyzerCmd::Ssr(cmd) => cmd.run()?,
89+
flags::RustAnalyzerCmd::Search(cmd) => cmd.run()?,
11290
}
11391
Ok(())
11492
}

crates/rust-analyzer/src/cli.rs

Lines changed: 7 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
11
//! Various batch processing tasks, intended primarily for debugging.
22
3+
pub mod flags;
34
pub mod load_cargo;
5+
mod parse;
6+
mod symbols;
7+
mod highlight;
48
mod analysis_stats;
59
mod diagnostics;
6-
mod progress_report;
710
mod ssr;
811

12+
mod progress_report;
13+
914
use std::io::Read;
1015

1116
use anyhow::Result;
12-
use ide::{Analysis, AnalysisHost};
13-
use syntax::{AstNode, SourceFile};
17+
use ide::AnalysisHost;
1418
use vfs::Vfs;
1519

16-
pub use self::{
17-
analysis_stats::AnalysisStatsCmd,
18-
diagnostics::diagnostics,
19-
ssr::{apply_ssr_rules, search_for_patterns},
20-
};
21-
2220
#[derive(Clone, Copy)]
2321
pub enum Verbosity {
2422
Spammy,
@@ -36,38 +34,6 @@ impl Verbosity {
3634
}
3735
}
3836

39-
pub fn parse(no_dump: bool) -> Result<()> {
40-
let _p = profile::span("parsing");
41-
let file = file()?;
42-
if !no_dump {
43-
println!("{:#?}", file.syntax());
44-
}
45-
std::mem::forget(file);
46-
Ok(())
47-
}
48-
49-
pub fn symbols() -> Result<()> {
50-
let text = read_stdin()?;
51-
let (analysis, file_id) = Analysis::from_single_file(text);
52-
let structure = analysis.file_structure(file_id).unwrap();
53-
for s in structure {
54-
println!("{:?}", s);
55-
}
56-
Ok(())
57-
}
58-
59-
pub fn highlight(rainbow: bool) -> Result<()> {
60-
let (analysis, file_id) = Analysis::from_single_file(read_stdin()?);
61-
let html = analysis.highlight_as_html(file_id, rainbow).unwrap();
62-
println!("{}", html);
63-
Ok(())
64-
}
65-
66-
fn file() -> Result<SourceFile> {
67-
let text = read_stdin()?;
68-
Ok(SourceFile::parse(&text).tree())
69-
}
70-
7137
fn read_stdin() -> Result<String> {
7238
let mut buff = String::new();
7339
std::io::stdin().read_to_string(&mut buff)?;

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

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
44
use std::{
55
env,
6-
path::PathBuf,
76
time::{SystemTime, UNIX_EPOCH},
87
};
98

@@ -28,6 +27,7 @@ use syntax::AstNode;
2827
use vfs::{Vfs, VfsPath};
2928

3029
use crate::cli::{
30+
flags,
3131
load_cargo::{load_workspace_at, LoadCargoConfig},
3232
print_memory_usage,
3333
progress_report::ProgressReport,
@@ -43,20 +43,7 @@ impl<DB: ParallelDatabase> Clone for Snap<salsa::Snapshot<DB>> {
4343
}
4444
}
4545

46-
pub struct AnalysisStatsCmd {
47-
pub randomize: bool,
48-
pub parallel: bool,
49-
pub memory_usage: bool,
50-
pub only: Option<String>,
51-
pub with_deps: bool,
52-
pub no_sysroot: bool,
53-
pub path: PathBuf,
54-
pub enable_build_scripts: bool,
55-
pub enable_proc_macros: bool,
56-
pub skip_inference: bool,
57-
}
58-
59-
impl AnalysisStatsCmd {
46+
impl flags::AnalysisStats {
6047
pub fn run(self, verbosity: Verbosity) -> Result<()> {
6148
let mut rng = {
6249
let seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
@@ -67,8 +54,8 @@ impl AnalysisStatsCmd {
6754
let mut cargo_config = CargoConfig::default();
6855
cargo_config.no_sysroot = self.no_sysroot;
6956
let load_cargo_config = LoadCargoConfig {
70-
load_out_dirs_from_check: self.enable_build_scripts,
71-
with_proc_macro: self.enable_proc_macros,
57+
load_out_dirs_from_check: !self.disable_build_scripts,
58+
with_proc_macro: !self.disable_proc_macros,
7259
prefill_caches: false,
7360
};
7461
let (host, vfs, _proc_macro) =
Lines changed: 61 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,86 @@
1-
//! Analyze all modules in a project for diagnostics. Exits with a non-zero status
2-
//! code if any errors are found.
1+
//! Analyze all modules in a project for diagnostics. Exits with a non-zero
2+
//! status code if any errors are found.
33
4-
use std::path::Path;
5-
6-
use anyhow::anyhow;
74
use rustc_hash::FxHashSet;
85

96
use hir::{db::HirDatabase, Crate, Module};
107
use ide::{AssistResolveStrategy, DiagnosticsConfig, Severity};
118
use ide_db::base_db::SourceDatabaseExt;
129

1310
use crate::cli::{
11+
flags,
1412
load_cargo::{load_workspace_at, LoadCargoConfig},
15-
Result,
1613
};
1714

18-
fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
19-
let mut worklist: Vec<_> =
20-
Crate::all(db).into_iter().map(|krate| krate.root_module(db)).collect();
21-
let mut modules = Vec::new();
15+
impl flags::Diagnostics {
16+
pub fn run(self) -> anyhow::Result<()> {
17+
let cargo_config = Default::default();
18+
let load_cargo_config = LoadCargoConfig {
19+
load_out_dirs_from_check: !self.disable_build_scripts,
20+
with_proc_macro: !self.disable_proc_macros,
21+
prefill_caches: false,
22+
};
23+
let (host, _vfs, _proc_macro) =
24+
load_workspace_at(&self.path, &cargo_config, &load_cargo_config, &|_| {})?;
25+
let db = host.raw_database();
26+
let analysis = host.analysis();
2227

23-
while let Some(module) = worklist.pop() {
24-
modules.push(module);
25-
worklist.extend(module.children(db));
26-
}
27-
28-
modules
29-
}
28+
let mut found_error = false;
29+
let mut visited_files = FxHashSet::default();
3030

31-
pub fn diagnostics(
32-
path: &Path,
33-
load_out_dirs_from_check: bool,
34-
with_proc_macro: bool,
35-
) -> Result<()> {
36-
let cargo_config = Default::default();
37-
let load_cargo_config =
38-
LoadCargoConfig { load_out_dirs_from_check, with_proc_macro, prefill_caches: false };
39-
let (host, _vfs, _proc_macro) =
40-
load_workspace_at(path, &cargo_config, &load_cargo_config, &|_| {})?;
41-
let db = host.raw_database();
42-
let analysis = host.analysis();
31+
let work = all_modules(db).into_iter().filter(|module| {
32+
let file_id = module.definition_source(db).file_id.original_file(db);
33+
let source_root = db.file_source_root(file_id);
34+
let source_root = db.source_root(source_root);
35+
!source_root.is_library
36+
});
4337

44-
let mut found_error = false;
45-
let mut visited_files = FxHashSet::default();
38+
for module in work {
39+
let file_id = module.definition_source(db).file_id.original_file(db);
40+
if !visited_files.contains(&file_id) {
41+
let crate_name =
42+
module.krate().display_name(db).as_deref().unwrap_or("unknown").to_string();
43+
println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id));
44+
for diagnostic in analysis
45+
.diagnostics(
46+
&DiagnosticsConfig::default(),
47+
AssistResolveStrategy::None,
48+
file_id,
49+
)
50+
.unwrap()
51+
{
52+
if matches!(diagnostic.severity, Severity::Error) {
53+
found_error = true;
54+
}
4655

47-
let work = all_modules(db).into_iter().filter(|module| {
48-
let file_id = module.definition_source(db).file_id.original_file(db);
49-
let source_root = db.file_source_root(file_id);
50-
let source_root = db.source_root(source_root);
51-
!source_root.is_library
52-
});
53-
54-
for module in work {
55-
let file_id = module.definition_source(db).file_id.original_file(db);
56-
if !visited_files.contains(&file_id) {
57-
let crate_name =
58-
module.krate().display_name(db).as_deref().unwrap_or("unknown").to_string();
59-
println!("processing crate: {}, module: {}", crate_name, _vfs.file_path(file_id));
60-
for diagnostic in analysis
61-
.diagnostics(&DiagnosticsConfig::default(), AssistResolveStrategy::None, file_id)
62-
.unwrap()
63-
{
64-
if matches!(diagnostic.severity, Severity::Error) {
65-
found_error = true;
56+
println!("{:?}", diagnostic);
6657
}
6758

68-
println!("{:?}", diagnostic);
59+
visited_files.insert(file_id);
6960
}
61+
}
62+
63+
println!();
64+
println!("diagnostic scan complete");
7065

71-
visited_files.insert(file_id);
66+
if found_error {
67+
println!();
68+
anyhow::bail!("diagnostic error detected")
7269
}
70+
71+
Ok(())
7372
}
73+
}
7474

75-
println!();
76-
println!("diagnostic scan complete");
75+
fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
76+
let mut worklist: Vec<_> =
77+
Crate::all(db).into_iter().map(|krate| krate.root_module(db)).collect();
78+
let mut modules = Vec::new();
7779

78-
if found_error {
79-
println!();
80-
Err(anyhow!("diagnostic error detected"))
81-
} else {
82-
Ok(())
80+
while let Some(module) = worklist.pop() {
81+
modules.push(module);
82+
worklist.extend(module.children(db));
8383
}
84+
85+
modules
8486
}

crates/rust-analyzer/src/bin/flags.rs renamed to crates/rust-analyzer/src/cli/flags.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
use std::path::PathBuf;
44

55
use ide_ssr::{SsrPattern, SsrRule};
6-
use rust_analyzer::cli::Verbosity;
6+
7+
use crate::cli::Verbosity;
78

89
xflags::xflags! {
910
src "./src/bin/flags.rs"
@@ -196,7 +197,7 @@ impl RustAnalyzer {
196197
// generated end
197198

198199
impl RustAnalyzer {
199-
pub(crate) fn verbosity(&self) -> Verbosity {
200+
pub fn verbosity(&self) -> Verbosity {
200201
if self.quiet {
201202
return Verbosity::Quiet;
202203
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
//! Read Rust code on stdin, print HTML highlighted version to stdout.
2+
3+
use ide::Analysis;
4+
5+
use crate::cli::{flags, read_stdin};
6+
7+
impl flags::Highlight {
8+
pub fn run(self) -> anyhow::Result<()> {
9+
let (analysis, file_id) = Analysis::from_single_file(read_stdin()?);
10+
let html = analysis.highlight_as_html(file_id, self.rainbow).unwrap();
11+
println!("{}", html);
12+
Ok(())
13+
}
14+
}

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//! Read Rust code on stdin, print syntax tree on stdout.
2+
use syntax::{AstNode, SourceFile};
3+
4+
use crate::cli::{flags, read_stdin};
5+
6+
impl flags::Parse {
7+
pub fn run(self) -> anyhow::Result<()> {
8+
let _p = profile::span("parsing");
9+
let text = read_stdin()?;
10+
let file = SourceFile::parse(&text).tree();
11+
if !self.no_dump {
12+
println!("{:#?}", file.syntax());
13+
}
14+
std::mem::forget(file);
15+
Ok(())
16+
}
17+
}

0 commit comments

Comments
 (0)