aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_cli
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2020-02-17 18:03:03 +0000
committerAleksey Kladov <[email protected]>2020-02-17 18:03:03 +0000
commit659b0e73cfd9ef7755d032f90622a08576f1d86d (patch)
tree238a2cb3e021502608d357785ebbe3b21f94573f /crates/ra_cli
parent2d1b3da5fb69d932c65884a361ec10d81e8a51d8 (diff)
Merge cli and ra_lsp_server
Diffstat (limited to 'crates/ra_cli')
-rw-r--r--crates/ra_cli/Cargo.toml31
-rw-r--r--crates/ra_cli/src/analysis_bench.rs127
-rw-r--r--crates/ra_cli/src/analysis_stats.rs259
-rw-r--r--crates/ra_cli/src/load_cargo.rs152
-rw-r--r--crates/ra_cli/src/main.rs336
-rw-r--r--crates/ra_cli/src/progress_report.rs120
6 files changed, 0 insertions, 1025 deletions
diff --git a/crates/ra_cli/Cargo.toml b/crates/ra_cli/Cargo.toml
deleted file mode 100644
index ce88a76b1..000000000
--- a/crates/ra_cli/Cargo.toml
+++ /dev/null
@@ -1,31 +0,0 @@
1[package]
2edition = "2018"
3name = "ra_cli"
4version = "0.1.0"
5authors = ["rust-analyzer developers"]
6publish = false
7
8[dependencies]
9crossbeam-channel = "0.4.0"
10env_logger = { version = "0.7.1", default-features = false }
11itertools = "0.8.0"
12log = "0.4.5"
13pico-args = "0.3.0"
14rand = { version = "0.7.0", features = ["small_rng"] }
15rustc-hash = "1.0"
16anyhow = "1.0"
17
18hir = { path = "../ra_hir", package = "ra_hir" }
19hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
20hir_ty = { path = "../ra_hir_ty", package = "ra_hir_ty" }
21ra_db = { path = "../ra_db" }
22ra_ide = { path = "../ra_ide" }
23ra_project_model = { path = "../ra_project_model" }
24ra_syntax = { path = "../ra_syntax" }
25ra_vfs = "0.5.0"
26ra_vfs_glob = { path = "../ra_vfs_glob" }
27
28[dependencies.ra_prof]
29path = "../ra_prof"
30# features = [ "cpu_profiler" ]
31# features = [ "jemalloc" ]
diff --git a/crates/ra_cli/src/analysis_bench.rs b/crates/ra_cli/src/analysis_bench.rs
deleted file mode 100644
index 91fc55fe2..000000000
--- a/crates/ra_cli/src/analysis_bench.rs
+++ /dev/null
@@ -1,127 +0,0 @@
1//! FIXME: write short doc here
2
3use std::{path::Path, sync::Arc, time::Instant};
4
5use anyhow::format_err;
6use ra_db::{
7 salsa::{Database, Durability},
8 FileId, SourceDatabaseExt,
9};
10use ra_ide::{Analysis, AnalysisChange, AnalysisHost, FilePosition, LineCol};
11
12use crate::{load_cargo::load_cargo, BenchWhat, Result, Verbosity};
13
14pub(crate) fn run(verbosity: Verbosity, path: &Path, what: BenchWhat) -> Result<()> {
15 ra_prof::init();
16
17 let start = Instant::now();
18 eprint!("loading: ");
19 let (mut host, roots) = load_cargo(path)?;
20 let db = host.raw_database();
21 eprintln!("{:?}\n", start.elapsed());
22
23 let file_id = {
24 let path = match &what {
25 BenchWhat::Highlight { path } => path,
26 BenchWhat::Complete(pos) | BenchWhat::GotoDef(pos) => &pos.path,
27 };
28 let path = std::env::current_dir()?.join(path).canonicalize()?;
29 roots
30 .iter()
31 .find_map(|(source_root_id, project_root)| {
32 if project_root.is_member() {
33 for file_id in db.source_root(*source_root_id).walk() {
34 let rel_path = db.file_relative_path(file_id);
35 let abs_path = rel_path.to_path(project_root.path());
36 if abs_path == path {
37 return Some(file_id);
38 }
39 }
40 }
41 None
42 })
43 .ok_or_else(|| format_err!("Can't find {}", path.display()))?
44 };
45
46 match &what {
47 BenchWhat::Highlight { .. } => {
48 let res = do_work(&mut host, file_id, |analysis| {
49 analysis.diagnostics(file_id).unwrap();
50 analysis.highlight_as_html(file_id, false).unwrap()
51 });
52 if verbosity.is_verbose() {
53 println!("\n{}", res);
54 }
55 }
56 BenchWhat::Complete(pos) | BenchWhat::GotoDef(pos) => {
57 let is_completion = match what {
58 BenchWhat::Complete(..) => true,
59 _ => false,
60 };
61
62 let offset = host
63 .analysis()
64 .file_line_index(file_id)?
65 .offset(LineCol { line: pos.line - 1, col_utf16: pos.column });
66 let file_postion = FilePosition { file_id, offset };
67
68 if is_completion {
69 let res =
70 do_work(&mut host, file_id, |analysis| analysis.completions(file_postion));
71 if verbosity.is_verbose() {
72 println!("\n{:#?}", res);
73 }
74 } else {
75 let res =
76 do_work(&mut host, file_id, |analysis| analysis.goto_definition(file_postion));
77 if verbosity.is_verbose() {
78 println!("\n{:#?}", res);
79 }
80 }
81 }
82 }
83 Ok(())
84}
85
86fn do_work<F: Fn(&Analysis) -> T, T>(host: &mut AnalysisHost, file_id: FileId, work: F) -> T {
87 {
88 let start = Instant::now();
89 eprint!("from scratch: ");
90 work(&host.analysis());
91 eprintln!("{:?}", start.elapsed());
92 }
93 {
94 let start = Instant::now();
95 eprint!("no change: ");
96 work(&host.analysis());
97 eprintln!("{:?}", start.elapsed());
98 }
99 {
100 let start = Instant::now();
101 eprint!("trivial change: ");
102 host.raw_database_mut().salsa_runtime_mut().synthetic_write(Durability::LOW);
103 work(&host.analysis());
104 eprintln!("{:?}", start.elapsed());
105 }
106 {
107 let start = Instant::now();
108 eprint!("comment change: ");
109 {
110 let mut text = host.analysis().file_text(file_id).unwrap().to_string();
111 text.push_str("\n/* Hello world */\n");
112 let mut change = AnalysisChange::new();
113 change.change_file(file_id, Arc::new(text));
114 host.apply_change(change);
115 }
116 work(&host.analysis());
117 eprintln!("{:?}", start.elapsed());
118 }
119 {
120 let start = Instant::now();
121 eprint!("const change: ");
122 host.raw_database_mut().salsa_runtime_mut().synthetic_write(Durability::HIGH);
123 let res = work(&host.analysis());
124 eprintln!("{:?}", start.elapsed());
125 res
126 }
127}
diff --git a/crates/ra_cli/src/analysis_stats.rs b/crates/ra_cli/src/analysis_stats.rs
deleted file mode 100644
index d40f04391..000000000
--- a/crates/ra_cli/src/analysis_stats.rs
+++ /dev/null
@@ -1,259 +0,0 @@
1//! FIXME: write short doc here
2
3use std::{collections::HashSet, fmt::Write, path::Path, time::Instant};
4
5use hir::{
6 db::{DefDatabase, HirDatabase},
7 AssocItem, Crate, HasSource, HirDisplay, ModuleDef,
8};
9use hir_def::FunctionId;
10use hir_ty::{Ty, TypeWalk};
11use itertools::Itertools;
12use ra_db::SourceDatabaseExt;
13use ra_syntax::AstNode;
14use rand::{seq::SliceRandom, thread_rng};
15
16use crate::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity};
17
18pub fn run(
19 verbosity: Verbosity,
20 memory_usage: bool,
21 path: &Path,
22 only: Option<&str>,
23 with_deps: bool,
24 randomize: bool,
25) -> Result<()> {
26 let db_load_time = Instant::now();
27 let (mut host, roots) = load_cargo(path)?;
28 let db = host.raw_database();
29 println!("Database loaded, {} roots, {:?}", roots.len(), db_load_time.elapsed());
30 let analysis_time = Instant::now();
31 let mut num_crates = 0;
32 let mut visited_modules = HashSet::new();
33 let mut visit_queue = Vec::new();
34
35 let members =
36 roots
37 .into_iter()
38 .filter_map(|(source_root_id, project_root)| {
39 if with_deps || project_root.is_member() {
40 Some(source_root_id)
41 } else {
42 None
43 }
44 })
45 .collect::<HashSet<_>>();
46
47 let mut krates = Crate::all(db);
48 if randomize {
49 krates.shuffle(&mut thread_rng());
50 }
51 for krate in krates {
52 let module = krate.root_module(db).expect("crate without root module");
53 let file_id = module.definition_source(db).file_id;
54 if members.contains(&db.file_source_root(file_id.original_file(db))) {
55 num_crates += 1;
56 visit_queue.push(module);
57 }
58 }
59
60 if randomize {
61 visit_queue.shuffle(&mut thread_rng());
62 }
63
64 println!("Crates in this dir: {}", num_crates);
65 let mut num_decls = 0;
66 let mut funcs = Vec::new();
67 while let Some(module) = visit_queue.pop() {
68 if visited_modules.insert(module) {
69 visit_queue.extend(module.children(db));
70
71 for decl in module.declarations(db) {
72 num_decls += 1;
73 if let ModuleDef::Function(f) = decl {
74 funcs.push(f);
75 }
76 }
77
78 for impl_block in module.impl_blocks(db) {
79 for item in impl_block.items(db) {
80 num_decls += 1;
81 if let AssocItem::Function(f) = item {
82 funcs.push(f);
83 }
84 }
85 }
86 }
87 }
88 println!("Total modules found: {}", visited_modules.len());
89 println!("Total declarations: {}", num_decls);
90 println!("Total functions: {}", funcs.len());
91 println!("Item Collection: {:?}, {}", analysis_time.elapsed(), ra_prof::memory_usage());
92
93 if randomize {
94 funcs.shuffle(&mut thread_rng());
95 }
96
97 let inference_time = Instant::now();
98 let mut bar = match verbosity {
99 Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(),
100 _ => ProgressReport::new(funcs.len() as u64),
101 };
102
103 bar.tick();
104 let mut num_exprs = 0;
105 let mut num_exprs_unknown = 0;
106 let mut num_exprs_partially_unknown = 0;
107 let mut num_type_mismatches = 0;
108 for f in funcs {
109 let name = f.name(db);
110 let full_name = f
111 .module(db)
112 .path_to_root(db)
113 .into_iter()
114 .rev()
115 .filter_map(|it| it.name(db))
116 .chain(Some(f.name(db)))
117 .join("::");
118 if let Some(only_name) = only {
119 if name.to_string() != only_name && full_name != only_name {
120 continue;
121 }
122 }
123 let mut msg = format!("processing: {}", full_name);
124 if verbosity.is_verbose() {
125 let src = f.source(db);
126 let original_file = src.file_id.original_file(db);
127 let path = db.file_relative_path(original_file);
128 let syntax_range = src.value.syntax().text_range();
129 write!(msg, " ({:?} {})", path, syntax_range).unwrap();
130 }
131 if verbosity.is_spammy() {
132 bar.println(format!("{}", msg));
133 }
134 bar.set_message(&msg);
135 let f_id = FunctionId::from(f);
136 let body = db.body(f_id.into());
137 let inference_result = db.infer(f_id.into());
138 let (previous_exprs, previous_unknown, previous_partially_unknown) =
139 (num_exprs, num_exprs_unknown, num_exprs_partially_unknown);
140 for (expr_id, _) in body.exprs.iter() {
141 let ty = &inference_result[expr_id];
142 num_exprs += 1;
143 if let Ty::Unknown = ty {
144 num_exprs_unknown += 1;
145 } else {
146 let mut is_partially_unknown = false;
147 ty.walk(&mut |ty| {
148 if let Ty::Unknown = ty {
149 is_partially_unknown = true;
150 }
151 });
152 if is_partially_unknown {
153 num_exprs_partially_unknown += 1;
154 }
155 }
156 if only.is_some() && verbosity.is_spammy() {
157 // in super-verbose mode for just one function, we print every single expression
158 let (_, sm) = db.body_with_source_map(f_id.into());
159 let src = sm.expr_syntax(expr_id);
160 if let Some(src) = src {
161 let original_file = src.file_id.original_file(db);
162 let line_index = host.analysis().file_line_index(original_file).unwrap();
163 let text_range = src.value.either(
164 |it| it.syntax_node_ptr().range(),
165 |it| it.syntax_node_ptr().range(),
166 );
167 let (start, end) = (
168 line_index.line_col(text_range.start()),
169 line_index.line_col(text_range.end()),
170 );
171 bar.println(format!(
172 "{}:{}-{}:{}: {}",
173 start.line + 1,
174 start.col_utf16,
175 end.line + 1,
176 end.col_utf16,
177 ty.display(db)
178 ));
179 } else {
180 bar.println(format!("unknown location: {}", ty.display(db)));
181 }
182 }
183 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr_id) {
184 num_type_mismatches += 1;
185 if verbosity.is_verbose() {
186 let (_, sm) = db.body_with_source_map(f_id.into());
187 let src = sm.expr_syntax(expr_id);
188 if let Some(src) = src {
189 // FIXME: it might be nice to have a function (on Analysis?) that goes from Source<T> -> (LineCol, LineCol) directly
190 let original_file = src.file_id.original_file(db);
191 let path = db.file_relative_path(original_file);
192 let line_index = host.analysis().file_line_index(original_file).unwrap();
193 let text_range = src.value.either(
194 |it| it.syntax_node_ptr().range(),
195 |it| it.syntax_node_ptr().range(),
196 );
197 let (start, end) = (
198 line_index.line_col(text_range.start()),
199 line_index.line_col(text_range.end()),
200 );
201 bar.println(format!(
202 "{} {}:{}-{}:{}: Expected {}, got {}",
203 path,
204 start.line + 1,
205 start.col_utf16,
206 end.line + 1,
207 end.col_utf16,
208 mismatch.expected.display(db),
209 mismatch.actual.display(db)
210 ));
211 } else {
212 bar.println(format!(
213 "{}: Expected {}, got {}",
214 name,
215 mismatch.expected.display(db),
216 mismatch.actual.display(db)
217 ));
218 }
219 }
220 }
221 }
222 if verbosity.is_spammy() {
223 bar.println(format!(
224 "In {}: {} exprs, {} unknown, {} partial",
225 full_name,
226 num_exprs - previous_exprs,
227 num_exprs_unknown - previous_unknown,
228 num_exprs_partially_unknown - previous_partially_unknown
229 ));
230 }
231 bar.inc(1);
232 }
233 bar.finish_and_clear();
234 println!("Total expressions: {}", num_exprs);
235 println!(
236 "Expressions of unknown type: {} ({}%)",
237 num_exprs_unknown,
238 if num_exprs > 0 { num_exprs_unknown * 100 / num_exprs } else { 100 }
239 );
240 println!(
241 "Expressions of partially unknown type: {} ({}%)",
242 num_exprs_partially_unknown,
243 if num_exprs > 0 { num_exprs_partially_unknown * 100 / num_exprs } else { 100 }
244 );
245 println!("Type mismatches: {}", num_type_mismatches);
246 println!("Inference: {:?}, {}", inference_time.elapsed(), ra_prof::memory_usage());
247 println!("Total: {:?}, {}", analysis_time.elapsed(), ra_prof::memory_usage());
248
249 if memory_usage {
250 for (name, bytes) in host.per_query_memory_usage() {
251 println!("{:>8} {}", bytes, name)
252 }
253 let before = ra_prof::memory_usage();
254 drop(host);
255 println!("leftover: {}", before.allocated - ra_prof::memory_usage().allocated)
256 }
257
258 Ok(())
259}
diff --git a/crates/ra_cli/src/load_cargo.rs b/crates/ra_cli/src/load_cargo.rs
deleted file mode 100644
index b9a4e6aba..000000000
--- a/crates/ra_cli/src/load_cargo.rs
+++ /dev/null
@@ -1,152 +0,0 @@
1//! FIXME: write short doc here
2
3use std::{collections::HashSet, path::Path};
4
5use crossbeam_channel::{unbounded, Receiver};
6use ra_db::{CrateGraph, FileId, SourceRootId};
7use ra_ide::{AnalysisChange, AnalysisHost, FeatureFlags};
8use ra_project_model::{get_rustc_cfg_options, PackageRoot, ProjectWorkspace};
9use ra_vfs::{RootEntry, Vfs, VfsChange, VfsTask, Watch};
10use ra_vfs_glob::RustPackageFilterBuilder;
11use rustc_hash::FxHashMap;
12
13use anyhow::Result;
14
15fn vfs_file_to_id(f: ra_vfs::VfsFile) -> FileId {
16 FileId(f.0)
17}
18fn vfs_root_to_id(r: ra_vfs::VfsRoot) -> SourceRootId {
19 SourceRootId(r.0)
20}
21
22pub fn load_cargo(root: &Path) -> Result<(AnalysisHost, FxHashMap<SourceRootId, PackageRoot>)> {
23 let root = std::env::current_dir()?.join(root);
24 let ws = ProjectWorkspace::discover(root.as_ref(), &Default::default())?;
25 let project_roots = ws.to_roots();
26 let (sender, receiver) = unbounded();
27 let sender = Box::new(move |t| sender.send(t).unwrap());
28 let (mut vfs, roots) = Vfs::new(
29 project_roots
30 .iter()
31 .map(|pkg_root| {
32 RootEntry::new(
33 pkg_root.path().clone(),
34 RustPackageFilterBuilder::default()
35 .set_member(pkg_root.is_member())
36 .into_vfs_filter(),
37 )
38 })
39 .collect(),
40 sender,
41 Watch(false),
42 );
43
44 // FIXME: cfg options?
45 let default_cfg_options = {
46 let mut opts = get_rustc_cfg_options();
47 opts.insert_atom("test".into());
48 opts.insert_atom("debug_assertion".into());
49 opts
50 };
51
52 let (crate_graph, _crate_names) =
53 ws.to_crate_graph(&default_cfg_options, &mut |path: &Path| {
54 let vfs_file = vfs.load(path);
55 log::debug!("vfs file {:?} -> {:?}", path, vfs_file);
56 vfs_file.map(vfs_file_to_id)
57 });
58 log::debug!("crate graph: {:?}", crate_graph);
59
60 let source_roots = roots
61 .iter()
62 .map(|&vfs_root| {
63 let source_root_id = vfs_root_to_id(vfs_root);
64 let project_root = project_roots
65 .iter()
66 .find(|it| it.path() == &vfs.root2path(vfs_root))
67 .unwrap()
68 .clone();
69 (source_root_id, project_root)
70 })
71 .collect::<FxHashMap<_, _>>();
72 let host = load(&source_roots, crate_graph, &mut vfs, receiver);
73 Ok((host, source_roots))
74}
75
76pub fn load(
77 source_roots: &FxHashMap<SourceRootId, PackageRoot>,
78 crate_graph: CrateGraph,
79 vfs: &mut Vfs,
80 receiver: Receiver<VfsTask>,
81) -> AnalysisHost {
82 let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<usize>().ok());
83 let mut host = AnalysisHost::new(lru_cap, FeatureFlags::default());
84 let mut analysis_change = AnalysisChange::new();
85 analysis_change.set_crate_graph(crate_graph);
86
87 // wait until Vfs has loaded all roots
88 let mut roots_loaded = HashSet::new();
89 for task in receiver {
90 vfs.handle_task(task);
91 let mut done = false;
92 for change in vfs.commit_changes() {
93 match change {
94 VfsChange::AddRoot { root, files } => {
95 let source_root_id = vfs_root_to_id(root);
96 let is_local = source_roots[&source_root_id].is_member();
97 log::debug!(
98 "loaded source root {:?} with path {:?}",
99 source_root_id,
100 vfs.root2path(root)
101 );
102 analysis_change.add_root(source_root_id, is_local);
103 analysis_change.set_debug_root_path(
104 source_root_id,
105 source_roots[&source_root_id].path().display().to_string(),
106 );
107
108 let mut file_map = FxHashMap::default();
109 for (vfs_file, path, text) in files {
110 let file_id = vfs_file_to_id(vfs_file);
111 analysis_change.add_file(source_root_id, file_id, path.clone(), text);
112 file_map.insert(path, file_id);
113 }
114 roots_loaded.insert(source_root_id);
115 if roots_loaded.len() == vfs.n_roots() {
116 done = true;
117 }
118 }
119 VfsChange::AddFile { root, file, path, text } => {
120 let source_root_id = vfs_root_to_id(root);
121 let file_id = vfs_file_to_id(file);
122 analysis_change.add_file(source_root_id, file_id, path, text);
123 }
124 VfsChange::RemoveFile { .. } | VfsChange::ChangeFile { .. } => {
125 // We just need the first scan, so just ignore these
126 }
127 }
128 }
129 if done {
130 break;
131 }
132 }
133
134 host.apply_change(analysis_change);
135 host
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 use hir::Crate;
143
144 #[test]
145 fn test_loading_rust_analyzer() {
146 let path = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().parent().unwrap();
147 let (host, _roots) = load_cargo(path).unwrap();
148 let n_crates = Crate::all(host.raw_database()).len();
149 // RA has quite a few crates, but the exact count doesn't matter
150 assert!(n_crates > 20);
151 }
152}
diff --git a/crates/ra_cli/src/main.rs b/crates/ra_cli/src/main.rs
deleted file mode 100644
index 4cf062f47..000000000
--- a/crates/ra_cli/src/main.rs
+++ /dev/null
@@ -1,336 +0,0 @@
1//! FIXME: write short doc here
2
3mod load_cargo;
4mod analysis_stats;
5mod analysis_bench;
6mod progress_report;
7
8use std::{fmt::Write, io::Read, path::PathBuf, str::FromStr};
9
10use pico_args::Arguments;
11use ra_ide::{file_structure, Analysis};
12use ra_prof::profile;
13use ra_syntax::{AstNode, SourceFile};
14
15use anyhow::{bail, format_err, Result};
16
17fn main() -> Result<()> {
18 env_logger::try_init()?;
19
20 let command = match Command::from_env_args()? {
21 Ok(it) => it,
22 Err(HelpPrinted) => return Ok(()),
23 };
24 match command {
25 Command::Parse { no_dump } => {
26 let _p = profile("parsing");
27 let file = file()?;
28 if !no_dump {
29 println!("{:#?}", file.syntax());
30 }
31 std::mem::forget(file);
32 }
33 Command::Symbols => {
34 let file = file()?;
35 for s in file_structure(&file) {
36 println!("{:?}", s);
37 }
38 }
39 Command::Highlight { rainbow } => {
40 let (analysis, file_id) = Analysis::from_single_file(read_stdin()?);
41 let html = analysis.highlight_as_html(file_id, rainbow).unwrap();
42 println!("{}", html);
43 }
44 Command::Stats { verbosity, randomize, memory_usage, only, with_deps, path } => {
45 analysis_stats::run(
46 verbosity,
47 memory_usage,
48 path.as_ref(),
49 only.as_ref().map(String::as_ref),
50 with_deps,
51 randomize,
52 )?;
53 }
54 Command::Bench { verbosity, path, what } => {
55 analysis_bench::run(verbosity, path.as_ref(), what)?;
56 }
57 }
58
59 Ok(())
60}
61
62enum Command {
63 Parse {
64 no_dump: bool,
65 },
66 Symbols,
67 Highlight {
68 rainbow: bool,
69 },
70 Stats {
71 verbosity: Verbosity,
72 randomize: bool,
73 memory_usage: bool,
74 only: Option<String>,
75 with_deps: bool,
76 path: PathBuf,
77 },
78 Bench {
79 verbosity: Verbosity,
80 path: PathBuf,
81 what: BenchWhat,
82 },
83}
84
85#[derive(Clone, Copy)]
86pub enum Verbosity {
87 Spammy,
88 Verbose,
89 Normal,
90 Quiet,
91}
92
93impl Verbosity {
94 fn is_verbose(self) -> bool {
95 match self {
96 Verbosity::Verbose | Verbosity::Spammy => true,
97 _ => false,
98 }
99 }
100 fn is_spammy(self) -> bool {
101 match self {
102 Verbosity::Spammy => true,
103 _ => false,
104 }
105 }
106}
107
108enum BenchWhat {
109 Highlight { path: PathBuf },
110 Complete(Position),
111 GotoDef(Position),
112}
113
114pub(crate) struct Position {
115 path: PathBuf,
116 line: u32,
117 column: u32,
118}
119
120impl FromStr for Position {
121 type Err = anyhow::Error;
122 fn from_str(s: &str) -> Result<Self> {
123 let (path_line, column) = rsplit_at_char(s, ':')?;
124 let (path, line) = rsplit_at_char(path_line, ':')?;
125 Ok(Position { path: path.into(), line: line.parse()?, column: column.parse()? })
126 }
127}
128
129fn rsplit_at_char(s: &str, c: char) -> Result<(&str, &str)> {
130 let idx = s.rfind(c).ok_or_else(|| format_err!("no `{}` in {}", c, s))?;
131 Ok((&s[..idx], &s[idx + 1..]))
132}
133
134struct HelpPrinted;
135
136impl Command {
137 fn from_env_args() -> Result<Result<Command, HelpPrinted>> {
138 let mut matches = Arguments::from_env();
139 let subcommand = matches.subcommand()?.unwrap_or_default();
140
141 let verbosity = match (
142 matches.contains(["-vv", "--spammy"]),
143 matches.contains(["-v", "--verbose"]),
144 matches.contains(["-q", "--quiet"]),
145 ) {
146 (true, _, true) => bail!("Invalid flags: -q conflicts with -vv"),
147 (true, _, false) => Verbosity::Spammy,
148 (false, false, false) => Verbosity::Normal,
149 (false, false, true) => Verbosity::Quiet,
150 (false, true, false) => Verbosity::Verbose,
151 (false, true, true) => bail!("Invalid flags: -q conflicts with -v"),
152 };
153
154 let command = match subcommand.as_str() {
155 "parse" => {
156 if matches.contains(["-h", "--help"]) {
157 eprintln!(
158 "\
159ra-cli-parse
160
161USAGE:
162 ra_cli parse [FLAGS]
163
164FLAGS:
165 -h, --help Prints help inforamtion
166 --no-dump"
167 );
168 return Ok(Err(HelpPrinted));
169 }
170
171 let no_dump = matches.contains("--no-dump");
172 matches.finish().or_else(handle_extra_flags)?;
173 Command::Parse { no_dump }
174 }
175 "symbols" => {
176 if matches.contains(["-h", "--help"]) {
177 eprintln!(
178 "\
179ra-cli-symbols
180
181USAGE:
182 ra_cli highlight [FLAGS]
183
184FLAGS:
185 -h, --help Prints help inforamtion"
186 );
187 return Ok(Err(HelpPrinted));
188 }
189
190 matches.finish().or_else(handle_extra_flags)?;
191
192 Command::Symbols
193 }
194 "highlight" => {
195 if matches.contains(["-h", "--help"]) {
196 eprintln!(
197 "\
198ra-cli-highlight
199
200USAGE:
201 ra_cli highlight [FLAGS]
202
203FLAGS:
204 -h, --help Prints help information
205 -r, --rainbow"
206 );
207 return Ok(Err(HelpPrinted));
208 }
209
210 let rainbow = matches.contains(["-r", "--rainbow"]);
211 matches.finish().or_else(handle_extra_flags)?;
212 Command::Highlight { rainbow }
213 }
214 "analysis-stats" => {
215 if matches.contains(["-h", "--help"]) {
216 eprintln!(
217 "\
218ra-cli-analysis-stats
219
220USAGE:
221 ra_cli analysis-stats [FLAGS] [OPTIONS] [PATH]
222
223FLAGS:
224 -h, --help Prints help information
225 --memory-usage
226 -v, --verbose
227 -q, --quiet
228
229OPTIONS:
230 -o <ONLY>
231
232ARGS:
233 <PATH>"
234 );
235 return Ok(Err(HelpPrinted));
236 }
237
238 let randomize = matches.contains("--randomize");
239 let memory_usage = matches.contains("--memory-usage");
240 let only: Option<String> = matches.opt_value_from_str(["-o", "--only"])?;
241 let with_deps: bool = matches.contains("--with-deps");
242 let path = {
243 let mut trailing = matches.free()?;
244 if trailing.len() != 1 {
245 bail!("Invalid flags");
246 }
247 trailing.pop().unwrap().into()
248 };
249
250 Command::Stats { verbosity, randomize, memory_usage, only, with_deps, path }
251 }
252 "analysis-bench" => {
253 if matches.contains(["-h", "--help"]) {
254 eprintln!(
255 "\
256ra_cli-analysis-bench
257
258USAGE:
259 ra_cli analysis-bench [FLAGS] [OPTIONS] [PATH]
260
261FLAGS:
262 -h, --help Prints help information
263 -v, --verbose
264
265OPTIONS:
266 --complete <PATH:LINE:COLUMN> Compute completions at this location
267 --highlight <PATH> Hightlight this file
268
269ARGS:
270 <PATH> Project to analyse"
271 );
272 return Ok(Err(HelpPrinted));
273 }
274
275 let path: PathBuf = matches.opt_value_from_str("--path")?.unwrap_or_default();
276 let highlight_path: Option<String> = matches.opt_value_from_str("--highlight")?;
277 let complete_path: Option<Position> = matches.opt_value_from_str("--complete")?;
278 let goto_def_path: Option<Position> = matches.opt_value_from_str("--goto-def")?;
279 let what = match (highlight_path, complete_path, goto_def_path) {
280 (Some(path), None, None) => BenchWhat::Highlight { path: path.into() },
281 (None, Some(position), None) => BenchWhat::Complete(position),
282 (None, None, Some(position)) => BenchWhat::GotoDef(position),
283 _ => panic!(
284 "exactly one of `--highlight`, `--complete` or `--goto-def` must be set"
285 ),
286 };
287 Command::Bench { verbosity, path, what }
288 }
289 _ => {
290 eprintln!(
291 "\
292ra-cli
293
294USAGE:
295 ra_cli <SUBCOMMAND>
296
297FLAGS:
298 -h, --help Prints help information
299
300SUBCOMMANDS:
301 analysis-bench
302 analysis-stats
303 highlight
304 parse
305 symbols"
306 );
307 return Ok(Err(HelpPrinted));
308 }
309 };
310 Ok(Ok(command))
311 }
312}
313
314fn handle_extra_flags(e: pico_args::Error) -> Result<()> {
315 if let pico_args::Error::UnusedArgsLeft(flags) = e {
316 let mut invalid_flags = String::new();
317 for flag in flags {
318 write!(&mut invalid_flags, "{}, ", flag)?;
319 }
320 let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2);
321 bail!("Invalid flags: {}", invalid_flags);
322 } else {
323 bail!(e);
324 }
325}
326
327fn file() -> Result<SourceFile> {
328 let text = read_stdin()?;
329 Ok(SourceFile::parse(&text).tree())
330}
331
332fn read_stdin() -> Result<String> {
333 let mut buff = String::new();
334 std::io::stdin().read_to_string(&mut buff)?;
335 Ok(buff)
336}
diff --git a/crates/ra_cli/src/progress_report.rs b/crates/ra_cli/src/progress_report.rs
deleted file mode 100644
index 31867a1e9..000000000
--- a/crates/ra_cli/src/progress_report.rs
+++ /dev/null
@@ -1,120 +0,0 @@
1//! A simple progress bar
2//!
3//! A single thread non-optimized progress bar
4use std::io::Write;
5
6/// A Simple ASCII Progress Bar
7pub struct ProgressReport {
8 curr: f32,
9 text: String,
10 hidden: bool,
11
12 len: u64,
13 pos: u64,
14 msg: String,
15}
16
17impl ProgressReport {
18 pub fn new(len: u64) -> ProgressReport {
19 ProgressReport {
20 curr: 0.0,
21 text: String::new(),
22 hidden: false,
23 len,
24 pos: 0,
25 msg: String::new(),
26 }
27 }
28
29 pub fn hidden() -> ProgressReport {
30 ProgressReport {
31 curr: 0.0,
32 text: String::new(),
33 hidden: true,
34 len: 0,
35 pos: 0,
36 msg: String::new(),
37 }
38 }
39
40 pub fn set_message(&mut self, msg: &str) {
41 self.msg = msg.to_string();
42 self.tick();
43 }
44
45 pub fn println<I: Into<String>>(&mut self, msg: I) {
46 self.clear();
47 println!("{}", msg.into());
48 self.tick();
49 }
50
51 pub fn inc(&mut self, delta: u64) {
52 self.pos += delta;
53 if self.len == 0 {
54 self.set_value(0.0)
55 } else {
56 self.set_value((self.pos as f32) / (self.len as f32))
57 }
58 self.tick();
59 }
60
61 pub fn finish_and_clear(&mut self) {
62 self.clear();
63 }
64
65 pub fn tick(&mut self) {
66 if self.hidden {
67 return;
68 }
69 let percent = (self.curr * 100.0) as u32;
70 let text = format!("{}/{} {:3>}% {}", self.pos, self.len, percent, self.msg);
71 self.update_text(&text);
72 }
73
74 fn update_text(&mut self, text: &str) {
75 // Get length of common portion
76 let mut common_prefix_length = 0;
77 let common_length = usize::min(self.text.len(), text.len());
78
79 while common_prefix_length < common_length
80 && text.chars().nth(common_prefix_length).unwrap()
81 == self.text.chars().nth(common_prefix_length).unwrap()
82 {
83 common_prefix_length += 1;
84 }
85
86 // Backtrack to the first differing character
87 let mut output = String::new();
88 output += &'\x08'.to_string().repeat(self.text.len() - common_prefix_length);
89 // Output new suffix
90 output += &text[common_prefix_length..text.len()];
91
92 // If the new text is shorter than the old one: delete overlapping characters
93 if let Some(overlap_count) = self.text.len().checked_sub(text.len()) {
94 if overlap_count > 0 {
95 output += &" ".repeat(overlap_count);
96 output += &"\x08".repeat(overlap_count);
97 }
98 }
99
100 let _ = std::io::stdout().write(output.as_bytes());
101 let _ = std::io::stdout().flush();
102 self.text = text.to_string();
103 }
104
105 fn set_value(&mut self, value: f32) {
106 self.curr = f32::max(0.0, f32::min(1.0, value));
107 }
108
109 fn clear(&mut self) {
110 if self.hidden {
111 return;
112 }
113
114 // Fill all last text to space and return the cursor
115 let spaces = " ".repeat(self.text.len());
116 let backspaces = "\x08".repeat(self.text.len());
117 print!("{}{}{}", backspaces, spaces, backspaces);
118 self.text = String::new();
119 }
120}