diff options
Diffstat (limited to 'crates/ra_lsp_server/src/cli')
-rw-r--r-- | crates/ra_lsp_server/src/cli/analysis_bench.rs | 158 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/cli/analysis_stats.rs | 259 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/cli/load_cargo.rs | 152 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/cli/progress_report.rs | 120 |
4 files changed, 689 insertions, 0 deletions
diff --git a/crates/ra_lsp_server/src/cli/analysis_bench.rs b/crates/ra_lsp_server/src/cli/analysis_bench.rs new file mode 100644 index 000000000..e00f81073 --- /dev/null +++ b/crates/ra_lsp_server/src/cli/analysis_bench.rs | |||
@@ -0,0 +1,158 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::{ | ||
4 | path::{Path, PathBuf}, | ||
5 | str::FromStr, | ||
6 | sync::Arc, | ||
7 | time::Instant, | ||
8 | }; | ||
9 | |||
10 | use anyhow::{format_err, Result}; | ||
11 | use ra_db::{ | ||
12 | salsa::{Database, Durability}, | ||
13 | FileId, SourceDatabaseExt, | ||
14 | }; | ||
15 | use ra_ide::{Analysis, AnalysisChange, AnalysisHost, FilePosition, LineCol}; | ||
16 | |||
17 | use crate::cli::{load_cargo::load_cargo, Verbosity}; | ||
18 | |||
19 | pub enum BenchWhat { | ||
20 | Highlight { path: PathBuf }, | ||
21 | Complete(Position), | ||
22 | GotoDef(Position), | ||
23 | } | ||
24 | |||
25 | pub struct Position { | ||
26 | pub path: PathBuf, | ||
27 | pub line: u32, | ||
28 | pub column: u32, | ||
29 | } | ||
30 | |||
31 | impl FromStr for Position { | ||
32 | type Err = anyhow::Error; | ||
33 | fn from_str(s: &str) -> Result<Self> { | ||
34 | let (path_line, column) = rsplit_at_char(s, ':')?; | ||
35 | let (path, line) = rsplit_at_char(path_line, ':')?; | ||
36 | Ok(Position { path: path.into(), line: line.parse()?, column: column.parse()? }) | ||
37 | } | ||
38 | } | ||
39 | |||
40 | fn rsplit_at_char(s: &str, c: char) -> Result<(&str, &str)> { | ||
41 | let idx = s.rfind(c).ok_or_else(|| format_err!("no `{}` in {}", c, s))?; | ||
42 | Ok((&s[..idx], &s[idx + 1..])) | ||
43 | } | ||
44 | |||
45 | pub fn analysis_bench(verbosity: Verbosity, path: &Path, what: BenchWhat) -> Result<()> { | ||
46 | ra_prof::init(); | ||
47 | |||
48 | let start = Instant::now(); | ||
49 | eprint!("loading: "); | ||
50 | let (mut host, roots) = load_cargo(path)?; | ||
51 | let db = host.raw_database(); | ||
52 | eprintln!("{:?}\n", start.elapsed()); | ||
53 | |||
54 | let file_id = { | ||
55 | let path = match &what { | ||
56 | BenchWhat::Highlight { path } => path, | ||
57 | BenchWhat::Complete(pos) | BenchWhat::GotoDef(pos) => &pos.path, | ||
58 | }; | ||
59 | let path = std::env::current_dir()?.join(path).canonicalize()?; | ||
60 | roots | ||
61 | .iter() | ||
62 | .find_map(|(source_root_id, project_root)| { | ||
63 | if project_root.is_member() { | ||
64 | for file_id in db.source_root(*source_root_id).walk() { | ||
65 | let rel_path = db.file_relative_path(file_id); | ||
66 | let abs_path = rel_path.to_path(project_root.path()); | ||
67 | if abs_path == path { | ||
68 | return Some(file_id); | ||
69 | } | ||
70 | } | ||
71 | } | ||
72 | None | ||
73 | }) | ||
74 | .ok_or_else(|| format_err!("Can't find {}", path.display()))? | ||
75 | }; | ||
76 | |||
77 | match &what { | ||
78 | BenchWhat::Highlight { .. } => { | ||
79 | let res = do_work(&mut host, file_id, |analysis| { | ||
80 | analysis.diagnostics(file_id).unwrap(); | ||
81 | analysis.highlight_as_html(file_id, false).unwrap() | ||
82 | }); | ||
83 | if verbosity.is_verbose() { | ||
84 | println!("\n{}", res); | ||
85 | } | ||
86 | } | ||
87 | BenchWhat::Complete(pos) | BenchWhat::GotoDef(pos) => { | ||
88 | let is_completion = match what { | ||
89 | BenchWhat::Complete(..) => true, | ||
90 | _ => false, | ||
91 | }; | ||
92 | |||
93 | let offset = host | ||
94 | .analysis() | ||
95 | .file_line_index(file_id)? | ||
96 | .offset(LineCol { line: pos.line - 1, col_utf16: pos.column }); | ||
97 | let file_postion = FilePosition { file_id, offset }; | ||
98 | |||
99 | if is_completion { | ||
100 | let res = | ||
101 | do_work(&mut host, file_id, |analysis| analysis.completions(file_postion)); | ||
102 | if verbosity.is_verbose() { | ||
103 | println!("\n{:#?}", res); | ||
104 | } | ||
105 | } else { | ||
106 | let res = | ||
107 | do_work(&mut host, file_id, |analysis| analysis.goto_definition(file_postion)); | ||
108 | if verbosity.is_verbose() { | ||
109 | println!("\n{:#?}", res); | ||
110 | } | ||
111 | } | ||
112 | } | ||
113 | } | ||
114 | Ok(()) | ||
115 | } | ||
116 | |||
117 | fn do_work<F: Fn(&Analysis) -> T, T>(host: &mut AnalysisHost, file_id: FileId, work: F) -> T { | ||
118 | { | ||
119 | let start = Instant::now(); | ||
120 | eprint!("from scratch: "); | ||
121 | work(&host.analysis()); | ||
122 | eprintln!("{:?}", start.elapsed()); | ||
123 | } | ||
124 | { | ||
125 | let start = Instant::now(); | ||
126 | eprint!("no change: "); | ||
127 | work(&host.analysis()); | ||
128 | eprintln!("{:?}", start.elapsed()); | ||
129 | } | ||
130 | { | ||
131 | let start = Instant::now(); | ||
132 | eprint!("trivial change: "); | ||
133 | host.raw_database_mut().salsa_runtime_mut().synthetic_write(Durability::LOW); | ||
134 | work(&host.analysis()); | ||
135 | eprintln!("{:?}", start.elapsed()); | ||
136 | } | ||
137 | { | ||
138 | let start = Instant::now(); | ||
139 | eprint!("comment change: "); | ||
140 | { | ||
141 | let mut text = host.analysis().file_text(file_id).unwrap().to_string(); | ||
142 | text.push_str("\n/* Hello world */\n"); | ||
143 | let mut change = AnalysisChange::new(); | ||
144 | change.change_file(file_id, Arc::new(text)); | ||
145 | host.apply_change(change); | ||
146 | } | ||
147 | work(&host.analysis()); | ||
148 | eprintln!("{:?}", start.elapsed()); | ||
149 | } | ||
150 | { | ||
151 | let start = Instant::now(); | ||
152 | eprint!("const change: "); | ||
153 | host.raw_database_mut().salsa_runtime_mut().synthetic_write(Durability::HIGH); | ||
154 | let res = work(&host.analysis()); | ||
155 | eprintln!("{:?}", start.elapsed()); | ||
156 | res | ||
157 | } | ||
158 | } | ||
diff --git a/crates/ra_lsp_server/src/cli/analysis_stats.rs b/crates/ra_lsp_server/src/cli/analysis_stats.rs new file mode 100644 index 000000000..c27fabe3c --- /dev/null +++ b/crates/ra_lsp_server/src/cli/analysis_stats.rs | |||
@@ -0,0 +1,259 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::{collections::HashSet, fmt::Write, path::Path, time::Instant}; | ||
4 | |||
5 | use hir::{ | ||
6 | db::{DefDatabase, HirDatabase}, | ||
7 | AssocItem, Crate, HasSource, HirDisplay, ModuleDef, | ||
8 | }; | ||
9 | use hir_def::FunctionId; | ||
10 | use hir_ty::{Ty, TypeWalk}; | ||
11 | use itertools::Itertools; | ||
12 | use ra_db::SourceDatabaseExt; | ||
13 | use ra_syntax::AstNode; | ||
14 | use rand::{seq::SliceRandom, thread_rng}; | ||
15 | |||
16 | use crate::cli::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity}; | ||
17 | |||
18 | pub fn analysis_stats( | ||
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_lsp_server/src/cli/load_cargo.rs b/crates/ra_lsp_server/src/cli/load_cargo.rs new file mode 100644 index 000000000..b9a4e6aba --- /dev/null +++ b/crates/ra_lsp_server/src/cli/load_cargo.rs | |||
@@ -0,0 +1,152 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::{collections::HashSet, path::Path}; | ||
4 | |||
5 | use crossbeam_channel::{unbounded, Receiver}; | ||
6 | use ra_db::{CrateGraph, FileId, SourceRootId}; | ||
7 | use ra_ide::{AnalysisChange, AnalysisHost, FeatureFlags}; | ||
8 | use ra_project_model::{get_rustc_cfg_options, PackageRoot, ProjectWorkspace}; | ||
9 | use ra_vfs::{RootEntry, Vfs, VfsChange, VfsTask, Watch}; | ||
10 | use ra_vfs_glob::RustPackageFilterBuilder; | ||
11 | use rustc_hash::FxHashMap; | ||
12 | |||
13 | use anyhow::Result; | ||
14 | |||
15 | fn vfs_file_to_id(f: ra_vfs::VfsFile) -> FileId { | ||
16 | FileId(f.0) | ||
17 | } | ||
18 | fn vfs_root_to_id(r: ra_vfs::VfsRoot) -> SourceRootId { | ||
19 | SourceRootId(r.0) | ||
20 | } | ||
21 | |||
22 | pub 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 | |||
76 | pub 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)] | ||
139 | mod 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_lsp_server/src/cli/progress_report.rs b/crates/ra_lsp_server/src/cli/progress_report.rs new file mode 100644 index 000000000..31867a1e9 --- /dev/null +++ b/crates/ra_lsp_server/src/cli/progress_report.rs | |||
@@ -0,0 +1,120 @@ | |||
1 | //! A simple progress bar | ||
2 | //! | ||
3 | //! A single thread non-optimized progress bar | ||
4 | use std::io::Write; | ||
5 | |||
6 | /// A Simple ASCII Progress Bar | ||
7 | pub struct ProgressReport { | ||
8 | curr: f32, | ||
9 | text: String, | ||
10 | hidden: bool, | ||
11 | |||
12 | len: u64, | ||
13 | pos: u64, | ||
14 | msg: String, | ||
15 | } | ||
16 | |||
17 | impl 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 | } | ||