aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_lsp_server/src
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_lsp_server/src
parent2d1b3da5fb69d932c65884a361ec10d81e8a51d8 (diff)
Merge cli and ra_lsp_server
Diffstat (limited to 'crates/ra_lsp_server/src')
-rw-r--r--crates/ra_lsp_server/src/args.rs237
-rw-r--r--crates/ra_lsp_server/src/cli.rs75
-rw-r--r--crates/ra_lsp_server/src/cli/analysis_bench.rs158
-rw-r--r--crates/ra_lsp_server/src/cli/analysis_stats.rs259
-rw-r--r--crates/ra_lsp_server/src/cli/load_cargo.rs152
-rw-r--r--crates/ra_lsp_server/src/cli/progress_report.rs120
-rw-r--r--crates/ra_lsp_server/src/lib.rs2
-rw-r--r--crates/ra_lsp_server/src/main.rs46
8 files changed, 1032 insertions, 17 deletions
diff --git a/crates/ra_lsp_server/src/args.rs b/crates/ra_lsp_server/src/args.rs
new file mode 100644
index 000000000..41959797c
--- /dev/null
+++ b/crates/ra_lsp_server/src/args.rs
@@ -0,0 +1,237 @@
1use anyhow::{bail, Result};
2use pico_args::Arguments;
3use ra_lsp_server::cli::{BenchWhat, Position, Verbosity};
4
5use std::{fmt::Write, path::PathBuf};
6
7pub(crate) struct Args {
8 pub(crate) verbosity: Verbosity,
9 pub(crate) command: Command,
10}
11
12pub(crate) enum Command {
13 Parse {
14 no_dump: bool,
15 },
16 Symbols,
17 Highlight {
18 rainbow: bool,
19 },
20 Stats {
21 randomize: bool,
22 memory_usage: bool,
23 only: Option<String>,
24 with_deps: bool,
25 path: PathBuf,
26 },
27 Bench {
28 path: PathBuf,
29 what: BenchWhat,
30 },
31 RunServer,
32 Version,
33}
34
35impl Args {
36 pub(crate) fn parse() -> Result<Result<Args, HelpPrinted>> {
37 let mut matches = Arguments::from_env();
38
39 if matches.contains("--version") {
40 matches.finish().or_else(handle_extra_flags)?;
41 return Ok(Ok(Args { verbosity: Verbosity::Normal, command: Command::Version }));
42 }
43
44 let verbosity = match (
45 matches.contains(["-vv", "--spammy"]),
46 matches.contains(["-v", "--verbose"]),
47 matches.contains(["-q", "--quiet"]),
48 ) {
49 (true, _, true) => bail!("Invalid flags: -q conflicts with -vv"),
50 (true, _, false) => Verbosity::Spammy,
51 (false, false, false) => Verbosity::Normal,
52 (false, false, true) => Verbosity::Quiet,
53 (false, true, false) => Verbosity::Verbose,
54 (false, true, true) => bail!("Invalid flags: -q conflicts with -v"),
55 };
56
57 let subcommand = match matches.subcommand()? {
58 Some(it) => it,
59 None => {
60 matches.finish().or_else(handle_extra_flags)?;
61 return Ok(Ok(Args { verbosity, command: Command::RunServer }));
62 }
63 };
64 let command = match subcommand.as_str() {
65 "parse" => {
66 if matches.contains(["-h", "--help"]) {
67 eprintln!(
68 "\
69ra-cli-parse
70
71USAGE:
72 ra_cli parse [FLAGS]
73
74FLAGS:
75 -h, --help Prints help inforamtion
76 --no-dump"
77 );
78 return Ok(Err(HelpPrinted));
79 }
80
81 let no_dump = matches.contains("--no-dump");
82 matches.finish().or_else(handle_extra_flags)?;
83 Command::Parse { no_dump }
84 }
85 "symbols" => {
86 if matches.contains(["-h", "--help"]) {
87 eprintln!(
88 "\
89ra-cli-symbols
90
91USAGE:
92 ra_cli highlight [FLAGS]
93
94FLAGS:
95 -h, --help Prints help inforamtion"
96 );
97 return Ok(Err(HelpPrinted));
98 }
99
100 matches.finish().or_else(handle_extra_flags)?;
101
102 Command::Symbols
103 }
104 "highlight" => {
105 if matches.contains(["-h", "--help"]) {
106 eprintln!(
107 "\
108ra-cli-highlight
109
110USAGE:
111 ra_cli highlight [FLAGS]
112
113FLAGS:
114 -h, --help Prints help information
115 -r, --rainbow"
116 );
117 return Ok(Err(HelpPrinted));
118 }
119
120 let rainbow = matches.contains(["-r", "--rainbow"]);
121 matches.finish().or_else(handle_extra_flags)?;
122 Command::Highlight { rainbow }
123 }
124 "analysis-stats" => {
125 if matches.contains(["-h", "--help"]) {
126 eprintln!(
127 "\
128ra-cli-analysis-stats
129
130USAGE:
131 ra_cli analysis-stats [FLAGS] [OPTIONS] [PATH]
132
133FLAGS:
134 -h, --help Prints help information
135 --memory-usage
136 -v, --verbose
137 -q, --quiet
138
139OPTIONS:
140 -o <ONLY>
141
142ARGS:
143 <PATH>"
144 );
145 return Ok(Err(HelpPrinted));
146 }
147
148 let randomize = matches.contains("--randomize");
149 let memory_usage = matches.contains("--memory-usage");
150 let only: Option<String> = matches.opt_value_from_str(["-o", "--only"])?;
151 let with_deps: bool = matches.contains("--with-deps");
152 let path = {
153 let mut trailing = matches.free()?;
154 if trailing.len() != 1 {
155 bail!("Invalid flags");
156 }
157 trailing.pop().unwrap().into()
158 };
159
160 Command::Stats { randomize, memory_usage, only, with_deps, path }
161 }
162 "analysis-bench" => {
163 if matches.contains(["-h", "--help"]) {
164 eprintln!(
165 "\
166ra_cli-analysis-bench
167
168USAGE:
169 ra_cli analysis-bench [FLAGS] [OPTIONS] [PATH]
170
171FLAGS:
172 -h, --help Prints help information
173 -v, --verbose
174
175OPTIONS:
176 --complete <PATH:LINE:COLUMN> Compute completions at this location
177 --highlight <PATH> Hightlight this file
178
179ARGS:
180 <PATH> Project to analyse"
181 );
182 return Ok(Err(HelpPrinted));
183 }
184
185 let path: PathBuf = matches.opt_value_from_str("--path")?.unwrap_or_default();
186 let highlight_path: Option<String> = matches.opt_value_from_str("--highlight")?;
187 let complete_path: Option<Position> = matches.opt_value_from_str("--complete")?;
188 let goto_def_path: Option<Position> = matches.opt_value_from_str("--goto-def")?;
189 let what = match (highlight_path, complete_path, goto_def_path) {
190 (Some(path), None, None) => BenchWhat::Highlight { path: path.into() },
191 (None, Some(position), None) => BenchWhat::Complete(position),
192 (None, None, Some(position)) => BenchWhat::GotoDef(position),
193 _ => panic!(
194 "exactly one of `--highlight`, `--complete` or `--goto-def` must be set"
195 ),
196 };
197 Command::Bench { path, what }
198 }
199 _ => {
200 eprintln!(
201 "\
202ra-cli
203
204USAGE:
205 ra_cli <SUBCOMMAND>
206
207FLAGS:
208 -h, --help Prints help information
209
210SUBCOMMANDS:
211 analysis-bench
212 analysis-stats
213 highlight
214 parse
215 symbols"
216 );
217 return Ok(Err(HelpPrinted));
218 }
219 };
220 Ok(Ok(Args { verbosity, command }))
221 }
222}
223
224pub(crate) struct HelpPrinted;
225
226fn handle_extra_flags(e: pico_args::Error) -> Result<()> {
227 if let pico_args::Error::UnusedArgsLeft(flags) = e {
228 let mut invalid_flags = String::new();
229 for flag in flags {
230 write!(&mut invalid_flags, "{}, ", flag)?;
231 }
232 let (invalid_flags, _) = invalid_flags.split_at(invalid_flags.len() - 2);
233 bail!("Invalid flags: {}", invalid_flags);
234 } else {
235 bail!(e);
236 }
237}
diff --git a/crates/ra_lsp_server/src/cli.rs b/crates/ra_lsp_server/src/cli.rs
new file mode 100644
index 000000000..3c7b8e250
--- /dev/null
+++ b/crates/ra_lsp_server/src/cli.rs
@@ -0,0 +1,75 @@
1//! FIXME: write short doc here
2
3mod load_cargo;
4mod analysis_stats;
5mod analysis_bench;
6mod progress_report;
7
8use std::io::Read;
9
10use anyhow::Result;
11use ra_ide::{file_structure, Analysis};
12use ra_prof::profile;
13use ra_syntax::{AstNode, SourceFile};
14
15#[derive(Clone, Copy)]
16pub enum Verbosity {
17 Spammy,
18 Verbose,
19 Normal,
20 Quiet,
21}
22
23impl Verbosity {
24 pub fn is_verbose(self) -> bool {
25 match self {
26 Verbosity::Verbose | Verbosity::Spammy => true,
27 _ => false,
28 }
29 }
30 pub fn is_spammy(self) -> bool {
31 match self {
32 Verbosity::Spammy => true,
33 _ => false,
34 }
35 }
36}
37
38pub fn parse(no_dump: bool) -> Result<()> {
39 let _p = profile("parsing");
40 let file = file()?;
41 if !no_dump {
42 println!("{:#?}", file.syntax());
43 }
44 std::mem::forget(file);
45 Ok(())
46}
47
48pub fn symbols() -> Result<()> {
49 let file = file()?;
50 for s in file_structure(&file) {
51 println!("{:?}", s);
52 }
53 Ok(())
54}
55
56pub fn highlight(rainbow: bool) -> Result<()> {
57 let (analysis, file_id) = Analysis::from_single_file(read_stdin()?);
58 let html = analysis.highlight_as_html(file_id, rainbow).unwrap();
59 println!("{}", html);
60 Ok(())
61}
62
63pub use analysis_bench::{analysis_bench, BenchWhat, Position};
64pub use analysis_stats::analysis_stats;
65
66fn file() -> Result<SourceFile> {
67 let text = read_stdin()?;
68 Ok(SourceFile::parse(&text).tree())
69}
70
71fn read_stdin() -> Result<String> {
72 let mut buff = String::new();
73 std::io::stdin().read_to_string(&mut buff)?;
74 Ok(buff)
75}
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
3use std::{
4 path::{Path, PathBuf},
5 str::FromStr,
6 sync::Arc,
7 time::Instant,
8};
9
10use anyhow::{format_err, Result};
11use ra_db::{
12 salsa::{Database, Durability},
13 FileId, SourceDatabaseExt,
14};
15use ra_ide::{Analysis, AnalysisChange, AnalysisHost, FilePosition, LineCol};
16
17use crate::cli::{load_cargo::load_cargo, Verbosity};
18
19pub enum BenchWhat {
20 Highlight { path: PathBuf },
21 Complete(Position),
22 GotoDef(Position),
23}
24
25pub struct Position {
26 pub path: PathBuf,
27 pub line: u32,
28 pub column: u32,
29}
30
31impl 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
40fn 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
45pub 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
117fn 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
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::cli::{load_cargo::load_cargo, progress_report::ProgressReport, Result, Verbosity};
17
18pub 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
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_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
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}
diff --git a/crates/ra_lsp_server/src/lib.rs b/crates/ra_lsp_server/src/lib.rs
index a3464a5a3..2832b2605 100644
--- a/crates/ra_lsp_server/src/lib.rs
+++ b/crates/ra_lsp_server/src/lib.rs
@@ -7,6 +7,8 @@
7//! state, and `main_loop` module defines the rules for modifying it. 7//! state, and `main_loop` module defines the rules for modifying it.
8#![recursion_limit = "512"] 8#![recursion_limit = "512"]
9 9
10pub mod cli;
11
10#[allow(unused)] 12#[allow(unused)]
11macro_rules! println { 13macro_rules! println {
12 ($($tt:tt)*) => { 14 ($($tt:tt)*) => {
diff --git a/crates/ra_lsp_server/src/main.rs b/crates/ra_lsp_server/src/main.rs
index ed2eaabd4..a549e5ff1 100644
--- a/crates/ra_lsp_server/src/main.rs
+++ b/crates/ra_lsp_server/src/main.rs
@@ -1,14 +1,39 @@
1//! `ra_lsp_server` binary 1//! `ra_lsp_server` binary
2mod args;
2 3
3use lsp_server::Connection; 4use lsp_server::Connection;
4use ra_lsp_server::{from_json, show_message, Result, ServerConfig}; 5use ra_lsp_server::{cli, from_json, show_message, Result, ServerConfig};
5use ra_prof; 6use ra_prof;
6 7
8use crate::args::HelpPrinted;
9
7fn main() -> Result<()> { 10fn main() -> Result<()> {
8 setup_logging()?; 11 setup_logging()?;
9 match Args::parse()? { 12 let args = match args::Args::parse()? {
10 Args::Version => println!("rust-analyzer {}", env!("REV")), 13 Ok(it) => it,
11 Args::Run => run_server()?, 14 Err(HelpPrinted) => return Ok(()),
15 };
16 match args.command {
17 args::Command::Parse { no_dump } => cli::parse(no_dump)?,
18 args::Command::Symbols => cli::symbols()?,
19 args::Command::Highlight { rainbow } => cli::highlight(rainbow)?,
20 args::Command::Stats { randomize, memory_usage, only, with_deps, path } => {
21 cli::analysis_stats(
22 args.verbosity,
23 memory_usage,
24 path.as_ref(),
25 only.as_ref().map(String::as_ref),
26 with_deps,
27 randomize,
28 )?
29 }
30
31 args::Command::Bench { path, what } => {
32 cli::analysis_bench(args.verbosity, path.as_ref(), what)?
33 }
34
35 args::Command::RunServer => run_server()?,
36 args::Command::Version => println!("rust-analyzer {}", env!("REV")),
12 } 37 }
13 Ok(()) 38 Ok(())
14} 39}
@@ -20,19 +45,6 @@ fn setup_logging() -> Result<()> {
20 Ok(()) 45 Ok(())
21} 46}
22 47
23enum Args {
24 Version,
25 Run,
26}
27
28impl Args {
29 fn parse() -> Result<Args> {
30 let res =
31 if std::env::args().any(|it| it == "--version") { Args::Version } else { Args::Run };
32 Ok(res)
33 }
34}
35
36fn run_server() -> Result<()> { 48fn run_server() -> Result<()> {
37 log::info!("lifecycle: server started"); 49 log::info!("lifecycle: server started");
38 50