aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_assists/src/handlers/add_explicit_type.rs2
-rw-r--r--crates/ra_assists/src/handlers/unwrap_block.rs221
-rw-r--r--crates/ra_assists/src/utils.rs4
-rw-r--r--crates/ra_flycheck/Cargo.toml2
-rw-r--r--crates/ra_flycheck/src/lib.rs2
-rw-r--r--crates/ra_hir/src/code_model.rs24
-rw-r--r--crates/ra_hir_def/src/data.rs31
-rw-r--r--crates/ra_hir_def/src/db.rs6
-rw-r--r--crates/ra_hir_expand/src/builtin_macro.rs4
-rw-r--r--crates/ra_hir_ty/src/display.rs63
-rw-r--r--crates/ra_hir_ty/src/infer.rs8
-rw-r--r--crates/ra_hir_ty/src/tests/display_source_code.rs27
-rw-r--r--crates/ra_ide/src/completion/complete_postfix.rs206
-rw-r--r--crates/ra_ide/src/completion/complete_snippet.rs26
-rw-r--r--crates/ra_ide/src/display/navigation_target.rs9
-rw-r--r--crates/ra_ide/src/references.rs25
-rw-r--r--crates/ra_ide/src/snapshots/highlight_strings.html4
-rw-r--r--crates/ra_ide/src/snapshots/highlighting.html23
-rw-r--r--crates/ra_ide/src/syntax_highlighting.rs33
-rw-r--r--crates/ra_ide/src/syntax_highlighting/tests.rs21
-rw-r--r--crates/ra_ide_db/src/defs.rs12
-rw-r--r--crates/ra_proc_macro_srv/Cargo.toml4
-rw-r--r--crates/ra_proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt21
-rw-r--r--crates/ra_proc_macro_srv/src/tests/mod.rs6
-rw-r--r--crates/ra_proc_macro_srv/src/tests/utils.rs4
-rw-r--r--crates/ra_project_model/Cargo.toml2
-rw-r--r--crates/ra_project_model/src/cargo_workspace.rs14
-rw-r--r--crates/ra_syntax/src/ast/make.rs7
-rw-r--r--crates/ra_text_edit/src/lib.rs1
-rw-r--r--crates/ra_toolchain/src/lib.rs7
-rw-r--r--crates/rust-analyzer/src/bin/main.rs7
-rw-r--r--crates/rust-analyzer/src/config.rs60
-rw-r--r--crates/rust-analyzer/src/conv.rs726
-rw-r--r--crates/rust-analyzer/src/from_proto.rs42
-rw-r--r--crates/rust-analyzer/src/lib.rs5
-rw-r--r--crates/rust-analyzer/src/lsp_ext.rs (renamed from crates/rust-analyzer/src/req.rs)29
-rw-r--r--crates/rust-analyzer/src/main_loop.rs198
-rw-r--r--crates/rust-analyzer/src/main_loop/handlers.rs519
-rw-r--r--crates/rust-analyzer/src/to_proto.rs592
-rw-r--r--crates/rust-analyzer/src/world.rs38
-rw-r--r--crates/rust-analyzer/tests/heavy_tests/main.rs17
-rw-r--r--crates/rust-analyzer/tests/heavy_tests/support.rs7
42 files changed, 1751 insertions, 1308 deletions
diff --git a/crates/ra_assists/src/handlers/add_explicit_type.rs b/crates/ra_assists/src/handlers/add_explicit_type.rs
index 146cc75df..7ced00626 100644
--- a/crates/ra_assists/src/handlers/add_explicit_type.rs
+++ b/crates/ra_assists/src/handlers/add_explicit_type.rs
@@ -209,7 +209,7 @@ struct Test<K, T = u8> {
209} 209}
210 210
211fn main() { 211fn main() {
212 let test<|>: Test<i32, u8> = Test { t: 23, k: 33 }; 212 let test<|>: Test<i32> = Test { t: 23, k: 33 };
213}"#, 213}"#,
214 ); 214 );
215 } 215 }
diff --git a/crates/ra_assists/src/handlers/unwrap_block.rs b/crates/ra_assists/src/handlers/unwrap_block.rs
index eba0631a4..e52ec557e 100644
--- a/crates/ra_assists/src/handlers/unwrap_block.rs
+++ b/crates/ra_assists/src/handlers/unwrap_block.rs
@@ -1,6 +1,6 @@
1use crate::{AssistContext, AssistId, Assists}; 1use crate::{AssistContext, AssistId, Assists};
2 2
3use ast::LoopBodyOwner; 3use ast::{ElseBranch, Expr, LoopBodyOwner};
4use ra_fmt::unwrap_trivial_block; 4use ra_fmt::unwrap_trivial_block;
5use ra_syntax::{ast, match_ast, AstNode, TextRange, T}; 5use ra_syntax::{ast, match_ast, AstNode, TextRange, T};
6 6
@@ -25,19 +25,11 @@ pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
25 let l_curly_token = ctx.find_token_at_offset(T!['{'])?; 25 let l_curly_token = ctx.find_token_at_offset(T!['{'])?;
26 let block = ast::BlockExpr::cast(l_curly_token.parent())?; 26 let block = ast::BlockExpr::cast(l_curly_token.parent())?;
27 let parent = block.syntax().parent()?; 27 let parent = block.syntax().parent()?;
28 let assist_id = AssistId("unwrap_block");
29 let assist_label = "Unwrap block";
30
28 let (expr, expr_to_unwrap) = match_ast! { 31 let (expr, expr_to_unwrap) = match_ast! {
29 match parent { 32 match parent {
30 ast::IfExpr(if_expr) => {
31 let expr_to_unwrap = if_expr.blocks().find_map(|expr| extract_expr(ctx.frange.range, expr));
32 let expr_to_unwrap = expr_to_unwrap?;
33 // Find if we are in a else if block
34 let ancestor = if_expr.syntax().parent().and_then(ast::IfExpr::cast);
35
36 match ancestor {
37 None => (ast::Expr::IfExpr(if_expr), expr_to_unwrap),
38 Some(ancestor) => (ast::Expr::IfExpr(ancestor), expr_to_unwrap),
39 }
40 },
41 ast::ForExpr(for_expr) => { 33 ast::ForExpr(for_expr) => {
42 let block_expr = for_expr.loop_body()?; 34 let block_expr = for_expr.loop_body()?;
43 let expr_to_unwrap = extract_expr(ctx.frange.range, block_expr)?; 35 let expr_to_unwrap = extract_expr(ctx.frange.range, block_expr)?;
@@ -53,27 +45,62 @@ pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
53 let expr_to_unwrap = extract_expr(ctx.frange.range, block_expr)?; 45 let expr_to_unwrap = extract_expr(ctx.frange.range, block_expr)?;
54 (ast::Expr::LoopExpr(loop_expr), expr_to_unwrap) 46 (ast::Expr::LoopExpr(loop_expr), expr_to_unwrap)
55 }, 47 },
48 ast::IfExpr(if_expr) => {
49 let mut resp = None;
50
51 let then_branch = if_expr.then_branch()?;
52 if then_branch.l_curly_token()?.text_range().contains_range(ctx.frange.range) {
53 if let Some(ancestor) = if_expr.syntax().parent().and_then(ast::IfExpr::cast) {
54 // For `else if` blocks
55 let ancestor_then_branch = ancestor.then_branch()?;
56 let l_curly_token = then_branch.l_curly_token()?;
57
58 let target = then_branch.syntax().text_range();
59 return acc.add(assist_id, assist_label, target, |edit| {
60 let range_to_del_else_if = TextRange::new(ancestor_then_branch.syntax().text_range().end(), l_curly_token.text_range().start());
61 let range_to_del_rest = TextRange::new(then_branch.syntax().text_range().end(), if_expr.syntax().text_range().end());
62
63 edit.set_cursor(ancestor_then_branch.syntax().text_range().end());
64 edit.delete(range_to_del_rest);
65 edit.delete(range_to_del_else_if);
66 edit.replace(target, update_expr_string(then_branch.to_string(), &[' ', '{']));
67 });
68 } else {
69 resp = Some((ast::Expr::IfExpr(if_expr.clone()), Expr::BlockExpr(then_branch)));
70 }
71 } else if let Some(else_branch) = if_expr.else_branch() {
72 match else_branch {
73 ElseBranch::Block(else_block) => {
74 let l_curly_token = else_block.l_curly_token()?;
75 if l_curly_token.text_range().contains_range(ctx.frange.range) {
76 let target = else_block.syntax().text_range();
77 return acc.add(assist_id, assist_label, target, |edit| {
78 let range_to_del = TextRange::new(then_branch.syntax().text_range().end(), l_curly_token.text_range().start());
79
80 edit.set_cursor(then_branch.syntax().text_range().end());
81 edit.delete(range_to_del);
82 edit.replace(target, update_expr_string(else_block.to_string(), &[' ', '{']));
83 });
84 }
85 },
86 ElseBranch::IfExpr(_) => {},
87 }
88 }
89
90 resp?
91 },
56 _ => return None, 92 _ => return None,
57 } 93 }
58 }; 94 };
59 95
60 let target = expr_to_unwrap.syntax().text_range(); 96 let target = expr_to_unwrap.syntax().text_range();
61 acc.add(AssistId("unwrap_block"), "Unwrap block", target, |edit| { 97 acc.add(assist_id, assist_label, target, |edit| {
62 edit.set_cursor(expr.syntax().text_range().start()); 98 edit.set_cursor(expr.syntax().text_range().start());
63 99
64 let pat_start: &[_] = &[' ', '{', '\n']; 100 edit.replace(
65 let expr_to_unwrap = expr_to_unwrap.to_string(); 101 expr.syntax().text_range(),
66 let expr_string = expr_to_unwrap.trim_start_matches(pat_start); 102 update_expr_string(expr_to_unwrap.to_string(), &[' ', '{', '\n']),
67 let mut expr_string_lines: Vec<&str> = expr_string.lines().collect(); 103 );
68 expr_string_lines.pop(); // Delete last line
69
70 let expr_string = expr_string_lines
71 .into_iter()
72 .map(|line| line.replacen(" ", "", 1)) // Delete indentation
73 .collect::<Vec<String>>()
74 .join("\n");
75
76 edit.replace(expr.syntax().text_range(), expr_string);
77 }) 104 })
78} 105}
79 106
@@ -87,6 +114,18 @@ fn extract_expr(cursor_range: TextRange, block: ast::BlockExpr) -> Option<ast::E
87 } 114 }
88} 115}
89 116
117fn update_expr_string(expr_str: String, trim_start_pat: &[char]) -> String {
118 let expr_string = expr_str.trim_start_matches(trim_start_pat);
119 let mut expr_string_lines: Vec<&str> = expr_string.lines().collect();
120 expr_string_lines.pop(); // Delete last line
121
122 expr_string_lines
123 .into_iter()
124 .map(|line| line.replacen(" ", "", 1)) // Delete indentation
125 .collect::<Vec<String>>()
126 .join("\n")
127}
128
90#[cfg(test)] 129#[cfg(test)]
91mod tests { 130mod tests {
92 use crate::tests::{check_assist, check_assist_not_applicable}; 131 use crate::tests::{check_assist, check_assist_not_applicable};
@@ -142,7 +181,13 @@ mod tests {
142 r#" 181 r#"
143 fn main() { 182 fn main() {
144 bar(); 183 bar();
145 <|>println!("bar"); 184 if true {
185 foo();
186
187 //comment
188 bar();
189 }<|>
190 println!("bar");
146 } 191 }
147 "#, 192 "#,
148 ); 193 );
@@ -170,7 +215,127 @@ mod tests {
170 r#" 215 r#"
171 fn main() { 216 fn main() {
172 //bar(); 217 //bar();
173 <|>println!("bar"); 218 if true {
219 println!("true");
220
221 //comment
222 //bar();
223 }<|>
224 println!("bar");
225 }
226 "#,
227 );
228 }
229
230 #[test]
231 fn simple_if_else_if_nested() {
232 check_assist(
233 unwrap_block,
234 r#"
235 fn main() {
236 //bar();
237 if true {
238 println!("true");
239
240 //comment
241 //bar();
242 } else if false {
243 println!("bar");
244 } else if true {<|>
245 println!("foo");
246 }
247 }
248 "#,
249 r#"
250 fn main() {
251 //bar();
252 if true {
253 println!("true");
254
255 //comment
256 //bar();
257 } else if false {
258 println!("bar");
259 }<|>
260 println!("foo");
261 }
262 "#,
263 );
264 }
265
266 #[test]
267 fn simple_if_else_if_nested_else() {
268 check_assist(
269 unwrap_block,
270 r#"
271 fn main() {
272 //bar();
273 if true {
274 println!("true");
275
276 //comment
277 //bar();
278 } else if false {
279 println!("bar");
280 } else if true {
281 println!("foo");
282 } else {<|>
283 println!("else");
284 }
285 }
286 "#,
287 r#"
288 fn main() {
289 //bar();
290 if true {
291 println!("true");
292
293 //comment
294 //bar();
295 } else if false {
296 println!("bar");
297 } else if true {
298 println!("foo");
299 }<|>
300 println!("else");
301 }
302 "#,
303 );
304 }
305
306 #[test]
307 fn simple_if_else_if_nested_middle() {
308 check_assist(
309 unwrap_block,
310 r#"
311 fn main() {
312 //bar();
313 if true {
314 println!("true");
315
316 //comment
317 //bar();
318 } else if false {
319 println!("bar");
320 } else if true {<|>
321 println!("foo");
322 } else {
323 println!("else");
324 }
325 }
326 "#,
327 r#"
328 fn main() {
329 //bar();
330 if true {
331 println!("true");
332
333 //comment
334 //bar();
335 } else if false {
336 println!("bar");
337 }<|>
338 println!("foo");
174 } 339 }
175 "#, 340 "#,
176 ); 341 );
diff --git a/crates/ra_assists/src/utils.rs b/crates/ra_assists/src/utils.rs
index 2f15a3f15..f3fc92ebf 100644
--- a/crates/ra_assists/src/utils.rs
+++ b/crates/ra_assists/src/utils.rs
@@ -103,7 +103,7 @@ fn invert_special_case(expr: &ast::Expr) -> Option<ast::Expr> {
103} 103}
104 104
105#[derive(Clone, Copy)] 105#[derive(Clone, Copy)]
106pub(crate) enum TryEnum { 106pub enum TryEnum {
107 Result, 107 Result,
108 Option, 108 Option,
109} 109}
@@ -111,7 +111,7 @@ pub(crate) enum TryEnum {
111impl TryEnum { 111impl TryEnum {
112 const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result]; 112 const ALL: [TryEnum; 2] = [TryEnum::Option, TryEnum::Result];
113 113
114 pub(crate) fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> { 114 pub fn from_ty(sema: &Semantics<RootDatabase>, ty: &Type) -> Option<TryEnum> {
115 let enum_ = match ty.as_adt() { 115 let enum_ = match ty.as_adt() {
116 Some(Adt::Enum(it)) => it, 116 Some(Adt::Enum(it)) => it,
117 _ => return None, 117 _ => return None,
diff --git a/crates/ra_flycheck/Cargo.toml b/crates/ra_flycheck/Cargo.toml
index 03e557148..eac502da5 100644
--- a/crates/ra_flycheck/Cargo.toml
+++ b/crates/ra_flycheck/Cargo.toml
@@ -11,7 +11,7 @@ doctest = false
11crossbeam-channel = "0.4.0" 11crossbeam-channel = "0.4.0"
12lsp-types = { version = "0.74.0", features = ["proposed"] } 12lsp-types = { version = "0.74.0", features = ["proposed"] }
13log = "0.4.8" 13log = "0.4.8"
14cargo_metadata = "0.9.1" 14cargo_metadata = "0.10.0"
15serde_json = "1.0.48" 15serde_json = "1.0.48"
16jod-thread = "0.1.1" 16jod-thread = "0.1.1"
17ra_toolchain = { path = "../ra_toolchain" } 17ra_toolchain = { path = "../ra_toolchain" }
diff --git a/crates/ra_flycheck/src/lib.rs b/crates/ra_flycheck/src/lib.rs
index 68dcee285..24af75c95 100644
--- a/crates/ra_flycheck/src/lib.rs
+++ b/crates/ra_flycheck/src/lib.rs
@@ -204,6 +204,8 @@ impl FlycheckThread {
204 } 204 }
205 205
206 CheckEvent::Msg(Message::BuildScriptExecuted(_msg)) => {} 206 CheckEvent::Msg(Message::BuildScriptExecuted(_msg)) => {}
207 CheckEvent::Msg(Message::BuildFinished(_)) => {}
208 CheckEvent::Msg(Message::TextLine(_)) => {}
207 CheckEvent::Msg(Message::Unknown) => {} 209 CheckEvent::Msg(Message::Unknown) => {}
208 } 210 }
209 } 211 }
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index be18c845c..e8e3211fc 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -148,6 +148,26 @@ impl ModuleDef {
148 ModuleDef::BuiltinType(_) => None, 148 ModuleDef::BuiltinType(_) => None,
149 } 149 }
150 } 150 }
151
152 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
153 let module = match self {
154 ModuleDef::Module(it) => it.parent(db)?,
155 ModuleDef::Function(it) => return Some(it.visibility(db)),
156 ModuleDef::Adt(it) => it.module(db),
157 ModuleDef::EnumVariant(it) => {
158 let parent = it.parent_enum(db);
159 let module = it.module(db);
160 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
161 }
162 ModuleDef::Const(it) => return Some(it.visibility(db)),
163 ModuleDef::Static(it) => it.module(db),
164 ModuleDef::Trait(it) => it.module(db),
165 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
166 ModuleDef::BuiltinType(_) => return None,
167 };
168
169 module.visibility_of(db, self)
170 }
151} 171}
152 172
153pub use hir_def::{ 173pub use hir_def::{
@@ -678,6 +698,10 @@ impl Static {
678 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { 698 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
679 db.static_data(self.id).name.clone() 699 db.static_data(self.id).name.clone()
680 } 700 }
701
702 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
703 db.static_data(self.id).mutable
704 }
681} 705}
682 706
683#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 707#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
diff --git a/crates/ra_hir_def/src/data.rs b/crates/ra_hir_def/src/data.rs
index e7eb2bb11..e2130d931 100644
--- a/crates/ra_hir_def/src/data.rs
+++ b/crates/ra_hir_def/src/data.rs
@@ -251,11 +251,6 @@ impl ConstData {
251 Arc::new(ConstData::new(db, vis_default, node)) 251 Arc::new(ConstData::new(db, vis_default, node))
252 } 252 }
253 253
254 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<ConstData> {
255 let node = konst.lookup(db).source(db);
256 Arc::new(ConstData::new(db, RawVisibility::private(), node))
257 }
258
259 fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>( 254 fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>(
260 db: &dyn DefDatabase, 255 db: &dyn DefDatabase,
261 vis_default: RawVisibility, 256 vis_default: RawVisibility,
@@ -270,6 +265,32 @@ impl ConstData {
270 } 265 }
271} 266}
272 267
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct StaticData {
270 pub name: Option<Name>,
271 pub type_ref: TypeRef,
272 pub visibility: RawVisibility,
273 pub mutable: bool,
274}
275
276impl StaticData {
277 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
278 let node = konst.lookup(db).source(db);
279 let ctx = LowerCtx::new(db, node.file_id);
280
281 let name = node.value.name().map(|n| n.as_name());
282 let type_ref = TypeRef::from_ast_opt(&ctx, node.value.ascribed_type());
283 let mutable = node.value.mut_token().is_some();
284 let visibility = RawVisibility::from_ast_with_default(
285 db,
286 RawVisibility::private(),
287 node.map(|n| n.visibility()),
288 );
289
290 Arc::new(StaticData { name, type_ref, visibility, mutable })
291 }
292}
293
273fn collect_items_in_macros( 294fn collect_items_in_macros(
274 db: &dyn DefDatabase, 295 db: &dyn DefDatabase,
275 expander: &mut Expander, 296 expander: &mut Expander,
diff --git a/crates/ra_hir_def/src/db.rs b/crates/ra_hir_def/src/db.rs
index 5dc7395f5..e665ab45d 100644
--- a/crates/ra_hir_def/src/db.rs
+++ b/crates/ra_hir_def/src/db.rs
@@ -10,7 +10,7 @@ use crate::{
10 adt::{EnumData, StructData}, 10 adt::{EnumData, StructData},
11 attr::Attrs, 11 attr::Attrs,
12 body::{scope::ExprScopes, Body, BodySourceMap}, 12 body::{scope::ExprScopes, Body, BodySourceMap},
13 data::{ConstData, FunctionData, ImplData, TraitData, TypeAliasData}, 13 data::{ConstData, FunctionData, ImplData, StaticData, TraitData, TypeAliasData},
14 docs::Documentation, 14 docs::Documentation,
15 generics::GenericParams, 15 generics::GenericParams,
16 lang_item::{LangItemTarget, LangItems}, 16 lang_item::{LangItemTarget, LangItems},
@@ -77,8 +77,8 @@ pub trait DefDatabase: InternDatabase + AstDatabase + Upcast<dyn AstDatabase> {
77 #[salsa::invoke(ConstData::const_data_query)] 77 #[salsa::invoke(ConstData::const_data_query)]
78 fn const_data(&self, konst: ConstId) -> Arc<ConstData>; 78 fn const_data(&self, konst: ConstId) -> Arc<ConstData>;
79 79
80 #[salsa::invoke(ConstData::static_data_query)] 80 #[salsa::invoke(StaticData::static_data_query)]
81 fn static_data(&self, konst: StaticId) -> Arc<ConstData>; 81 fn static_data(&self, konst: StaticId) -> Arc<StaticData>;
82 82
83 #[salsa::invoke(Body::body_with_source_map_query)] 83 #[salsa::invoke(Body::body_with_source_map_query)]
84 fn body_with_source_map(&self, def: DefWithBodyId) -> (Arc<Body>, Arc<BodySourceMap>); 84 fn body_with_source_map(&self, def: DefWithBodyId) -> (Arc<Body>, Arc<BodySourceMap>);
diff --git a/crates/ra_hir_expand/src/builtin_macro.rs b/crates/ra_hir_expand/src/builtin_macro.rs
index d8b3d342c..3bce8f673 100644
--- a/crates/ra_hir_expand/src/builtin_macro.rs
+++ b/crates/ra_hir_expand/src/builtin_macro.rs
@@ -360,7 +360,7 @@ fn env_expand(
360 // However, we cannot use an empty string here, because for 360 // However, we cannot use an empty string here, because for
361 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become 361 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
362 // `include!("foo.rs"), which might go to infinite loop 362 // `include!("foo.rs"), which might go to infinite loop
363 let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| "__RA_UNIMPLEMENTATED__".to_string()); 363 let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| "__RA_UNIMPLEMENTED__".to_string());
364 let expanded = quote! { #s }; 364 let expanded = quote! { #s };
365 365
366 Ok((expanded, FragmentKind::Expr)) 366 Ok((expanded, FragmentKind::Expr))
@@ -508,7 +508,7 @@ mod tests {
508 "#, 508 "#,
509 ); 509 );
510 510
511 assert_eq!(expanded, "\"__RA_UNIMPLEMENTATED__\""); 511 assert_eq!(expanded, "\"__RA_UNIMPLEMENTED__\"");
512 } 512 }
513 513
514 #[test] 514 #[test]
diff --git a/crates/ra_hir_ty/src/display.rs b/crates/ra_hir_ty/src/display.rs
index f5edaea8c..b9c4d2e89 100644
--- a/crates/ra_hir_ty/src/display.rs
+++ b/crates/ra_hir_ty/src/display.rs
@@ -136,6 +136,12 @@ enum DisplayTarget {
136 SourceCode { module_id: ModuleId }, 136 SourceCode { module_id: ModuleId },
137} 137}
138 138
139impl DisplayTarget {
140 fn is_source_code(&self) -> bool {
141 matches!(self, Self::SourceCode {..})
142 }
143}
144
139#[derive(Debug)] 145#[derive(Debug)]
140pub enum DisplaySourceCodeError { 146pub enum DisplaySourceCodeError {
141 PathNotFound, 147 PathNotFound,
@@ -303,37 +309,40 @@ impl HirDisplay for ApplicationTy {
303 309
304 if self.parameters.len() > 0 { 310 if self.parameters.len() > 0 {
305 let mut non_default_parameters = Vec::with_capacity(self.parameters.len()); 311 let mut non_default_parameters = Vec::with_capacity(self.parameters.len());
306 let parameters_to_write = if f.omit_verbose_types() { 312 let parameters_to_write =
307 match self 313 if f.display_target.is_source_code() || f.omit_verbose_types() {
308 .ctor 314 match self
309 .as_generic_def() 315 .ctor
310 .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) 316 .as_generic_def()
311 .filter(|defaults| !defaults.is_empty()) 317 .map(|generic_def_id| f.db.generic_defaults(generic_def_id))
312 { 318 .filter(|defaults| !defaults.is_empty())
313 None => self.parameters.0.as_ref(), 319 {
314 Some(default_parameters) => { 320 None => self.parameters.0.as_ref(),
315 for (i, parameter) in self.parameters.iter().enumerate() { 321 Some(default_parameters) => {
316 match (parameter, default_parameters.get(i)) { 322 for (i, parameter) in self.parameters.iter().enumerate() {
317 (&Ty::Unknown, _) | (_, None) => { 323 match (parameter, default_parameters.get(i)) {
318 non_default_parameters.push(parameter.clone()) 324 (&Ty::Unknown, _) | (_, None) => {
319 } 325 non_default_parameters.push(parameter.clone())
320 (_, Some(default_parameter)) 326 }
321 if parameter != default_parameter => 327 (_, Some(default_parameter))
322 { 328 if parameter != default_parameter =>
323 non_default_parameters.push(parameter.clone()) 329 {
330 non_default_parameters.push(parameter.clone())
331 }
332 _ => (),
324 } 333 }
325 _ => (),
326 } 334 }
335 &non_default_parameters
327 } 336 }
328 &non_default_parameters
329 } 337 }
330 } 338 } else {
331 } else { 339 self.parameters.0.as_ref()
332 self.parameters.0.as_ref() 340 };
333 }; 341 if !parameters_to_write.is_empty() {
334 write!(f, "<")?; 342 write!(f, "<")?;
335 f.write_joined(parameters_to_write, ", ")?; 343 f.write_joined(parameters_to_write, ", ")?;
336 write!(f, ">")?; 344 write!(f, ">")?;
345 }
337 } 346 }
338 } 347 }
339 TypeCtor::AssociatedType(type_alias) => { 348 TypeCtor::AssociatedType(type_alias) => {
diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs
index a21ad8d86..fb7c6cd8c 100644
--- a/crates/ra_hir_ty/src/infer.rs
+++ b/crates/ra_hir_ty/src/infer.rs
@@ -22,7 +22,7 @@ use rustc_hash::FxHashMap;
22 22
23use hir_def::{ 23use hir_def::{
24 body::Body, 24 body::Body,
25 data::{ConstData, FunctionData}, 25 data::{ConstData, FunctionData, StaticData},
26 expr::{BindingAnnotation, ExprId, PatId}, 26 expr::{BindingAnnotation, ExprId, PatId},
27 lang_item::LangItemTarget, 27 lang_item::LangItemTarget,
28 path::{path, Path}, 28 path::{path, Path},
@@ -71,7 +71,7 @@ pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<Infer
71 match def { 71 match def {
72 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)), 72 DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
73 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)), 73 DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
74 DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)), 74 DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
75 } 75 }
76 76
77 ctx.infer_body(); 77 ctx.infer_body();
@@ -485,6 +485,10 @@ impl<'a> InferenceContext<'a> {
485 self.return_ty = self.make_ty(&data.type_ref); 485 self.return_ty = self.make_ty(&data.type_ref);
486 } 486 }
487 487
488 fn collect_static(&mut self, data: &StaticData) {
489 self.return_ty = self.make_ty(&data.type_ref);
490 }
491
488 fn collect_fn(&mut self, data: &FunctionData) { 492 fn collect_fn(&mut self, data: &FunctionData) {
489 let body = Arc::clone(&self.body); // avoid borrow checker problem 493 let body = Arc::clone(&self.body); // avoid borrow checker problem
490 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) 494 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)
diff --git a/crates/ra_hir_ty/src/tests/display_source_code.rs b/crates/ra_hir_ty/src/tests/display_source_code.rs
index ca1748615..4088b1d22 100644
--- a/crates/ra_hir_ty/src/tests/display_source_code.rs
+++ b/crates/ra_hir_ty/src/tests/display_source_code.rs
@@ -21,3 +21,30 @@ fn bar() {
21 ); 21 );
22 assert_eq!("foo::Foo", displayed_source_at_pos(&db, pos)); 22 assert_eq!("foo::Foo", displayed_source_at_pos(&db, pos));
23} 23}
24
25#[test]
26fn omit_default_type_parameters() {
27 let (db, pos) = TestDB::with_position(
28 r"
29 //- /main.rs
30 struct Foo<T = u8> { t: T }
31 fn main() {
32 let foo = Foo { t: 5 };
33 foo<|>;
34 }
35 ",
36 );
37 assert_eq!("Foo", displayed_source_at_pos(&db, pos));
38
39 let (db, pos) = TestDB::with_position(
40 r"
41 //- /main.rs
42 struct Foo<K, T = u8> { k: K, t: T }
43 fn main() {
44 let foo = Foo { k: 400, t: 5 };
45 foo<|>;
46 }
47 ",
48 );
49 assert_eq!("Foo<i32>", displayed_source_at_pos(&db, pos));
50}
diff --git a/crates/ra_ide/src/completion/complete_postfix.rs b/crates/ra_ide/src/completion/complete_postfix.rs
index 6a0f0c72e..c5c4426cc 100644
--- a/crates/ra_ide/src/completion/complete_postfix.rs
+++ b/crates/ra_ide/src/completion/complete_postfix.rs
@@ -14,6 +14,7 @@ use crate::{
14 }, 14 },
15 CompletionItem, 15 CompletionItem,
16}; 16};
17use ra_assists::utils::TryEnum;
17 18
18pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) { 19pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
19 if !ctx.config.enable_postfix_completions { 20 if !ctx.config.enable_postfix_completions {
@@ -38,7 +39,52 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
38 None => return, 39 None => return,
39 }; 40 };
40 41
41 if receiver_ty.is_bool() || receiver_ty.is_unknown() { 42 if let Some(try_enum) = TryEnum::from_ty(&ctx.sema, &receiver_ty) {
43 match try_enum {
44 TryEnum::Result => {
45 postfix_snippet(
46 ctx,
47 cap,
48 &dot_receiver,
49 "ifl",
50 "if let Ok {}",
51 &format!("if let Ok($1) = {} {{\n $0\n}}", receiver_text),
52 )
53 .add_to(acc);
54
55 postfix_snippet(
56 ctx,
57 cap,
58 &dot_receiver,
59 "while",
60 "while let Ok {}",
61 &format!("while let Ok($1) = {} {{\n $0\n}}", receiver_text),
62 )
63 .add_to(acc);
64 }
65 TryEnum::Option => {
66 postfix_snippet(
67 ctx,
68 cap,
69 &dot_receiver,
70 "ifl",
71 "if let Some {}",
72 &format!("if let Some($1) = {} {{\n $0\n}}", receiver_text),
73 )
74 .add_to(acc);
75
76 postfix_snippet(
77 ctx,
78 cap,
79 &dot_receiver,
80 "while",
81 "while let Some {}",
82 &format!("while let Some($1) = {} {{\n $0\n}}", receiver_text),
83 )
84 .add_to(acc);
85 }
86 }
87 } else if receiver_ty.is_bool() || receiver_ty.is_unknown() {
42 postfix_snippet( 88 postfix_snippet(
43 ctx, 89 ctx,
44 cap, 90 cap,
@@ -236,6 +282,164 @@ mod tests {
236 } 282 }
237 283
238 #[test] 284 #[test]
285 fn postfix_completion_works_for_option() {
286 assert_debug_snapshot!(
287 do_postfix_completion(
288 r#"
289 enum Option<T> {
290 Some(T),
291 None,
292 }
293
294 fn main() {
295 let bar = Option::Some(true);
296 bar.<|>
297 }
298 "#,
299 ),
300 @r###"
301 [
302 CompletionItem {
303 label: "box",
304 source_range: 210..210,
305 delete: 206..210,
306 insert: "Box::new(bar)",
307 detail: "Box::new(expr)",
308 },
309 CompletionItem {
310 label: "dbg",
311 source_range: 210..210,
312 delete: 206..210,
313 insert: "dbg!(bar)",
314 detail: "dbg!(expr)",
315 },
316 CompletionItem {
317 label: "ifl",
318 source_range: 210..210,
319 delete: 206..210,
320 insert: "if let Some($1) = bar {\n $0\n}",
321 detail: "if let Some {}",
322 },
323 CompletionItem {
324 label: "match",
325 source_range: 210..210,
326 delete: 206..210,
327 insert: "match bar {\n ${1:_} => {$0\\},\n}",
328 detail: "match expr {}",
329 },
330 CompletionItem {
331 label: "not",
332 source_range: 210..210,
333 delete: 206..210,
334 insert: "!bar",
335 detail: "!expr",
336 },
337 CompletionItem {
338 label: "ref",
339 source_range: 210..210,
340 delete: 206..210,
341 insert: "&bar",
342 detail: "&expr",
343 },
344 CompletionItem {
345 label: "refm",
346 source_range: 210..210,
347 delete: 206..210,
348 insert: "&mut bar",
349 detail: "&mut expr",
350 },
351 CompletionItem {
352 label: "while",
353 source_range: 210..210,
354 delete: 206..210,
355 insert: "while let Some($1) = bar {\n $0\n}",
356 detail: "while let Some {}",
357 },
358 ]
359 "###
360 );
361 }
362
363 #[test]
364 fn postfix_completion_works_for_result() {
365 assert_debug_snapshot!(
366 do_postfix_completion(
367 r#"
368 enum Result<T, E> {
369 Ok(T),
370 Err(E),
371 }
372
373 fn main() {
374 let bar = Result::Ok(true);
375 bar.<|>
376 }
377 "#,
378 ),
379 @r###"
380 [
381 CompletionItem {
382 label: "box",
383 source_range: 211..211,
384 delete: 207..211,
385 insert: "Box::new(bar)",
386 detail: "Box::new(expr)",
387 },
388 CompletionItem {
389 label: "dbg",
390 source_range: 211..211,
391 delete: 207..211,
392 insert: "dbg!(bar)",
393 detail: "dbg!(expr)",
394 },
395 CompletionItem {
396 label: "ifl",
397 source_range: 211..211,
398 delete: 207..211,
399 insert: "if let Ok($1) = bar {\n $0\n}",
400 detail: "if let Ok {}",
401 },
402 CompletionItem {
403 label: "match",
404 source_range: 211..211,
405 delete: 207..211,
406 insert: "match bar {\n ${1:_} => {$0\\},\n}",
407 detail: "match expr {}",
408 },
409 CompletionItem {
410 label: "not",
411 source_range: 211..211,
412 delete: 207..211,
413 insert: "!bar",
414 detail: "!expr",
415 },
416 CompletionItem {
417 label: "ref",
418 source_range: 211..211,
419 delete: 207..211,
420 insert: "&bar",
421 detail: "&expr",
422 },
423 CompletionItem {
424 label: "refm",
425 source_range: 211..211,
426 delete: 207..211,
427 insert: "&mut bar",
428 detail: "&mut expr",
429 },
430 CompletionItem {
431 label: "while",
432 source_range: 211..211,
433 delete: 207..211,
434 insert: "while let Ok($1) = bar {\n $0\n}",
435 detail: "while let Ok {}",
436 },
437 ]
438 "###
439 );
440 }
441
442 #[test]
239 fn some_postfix_completions_ignored() { 443 fn some_postfix_completions_ignored() {
240 assert_debug_snapshot!( 444 assert_debug_snapshot!(
241 do_postfix_completion( 445 do_postfix_completion(
diff --git a/crates/ra_ide/src/completion/complete_snippet.rs b/crates/ra_ide/src/completion/complete_snippet.rs
index a3f5d1b6a..0568d9ccf 100644
--- a/crates/ra_ide/src/completion/complete_snippet.rs
+++ b/crates/ra_ide/src/completion/complete_snippet.rs
@@ -36,6 +36,24 @@ pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionConte
36 snippet( 36 snippet(
37 ctx, 37 ctx,
38 cap, 38 cap,
39 "Test module",
40 "\
41#[cfg(test)]
42mod tests {
43 use super::*;
44
45 #[test]
46 fn ${1:test_name}() {
47 $0
48 }
49}",
50 )
51 .lookup_by("tmod")
52 .add_to(acc);
53
54 snippet(
55 ctx,
56 cap,
39 "Test function", 57 "Test function",
40 "\ 58 "\
41#[test] 59#[test]
@@ -118,6 +136,14 @@ mod tests {
118 lookup: "tfn", 136 lookup: "tfn",
119 }, 137 },
120 CompletionItem { 138 CompletionItem {
139 label: "Test module",
140 source_range: 78..78,
141 delete: 78..78,
142 insert: "#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn ${1:test_name}() {\n $0\n }\n}",
143 kind: Snippet,
144 lookup: "tmod",
145 },
146 CompletionItem {
121 label: "macro_rules", 147 label: "macro_rules",
122 source_range: 78..78, 148 source_range: 78..78,
123 delete: 78..78, 149 delete: 78..78,
diff --git a/crates/ra_ide/src/display/navigation_target.rs b/crates/ra_ide/src/display/navigation_target.rs
index de35c6711..5da28edd2 100644
--- a/crates/ra_ide/src/display/navigation_target.rs
+++ b/crates/ra_ide/src/display/navigation_target.rs
@@ -11,7 +11,7 @@ use ra_syntax::{
11 TextRange, 11 TextRange,
12}; 12};
13 13
14use crate::FileSymbol; 14use crate::{FileRange, FileSymbol};
15 15
16use super::short_label::ShortLabel; 16use super::short_label::ShortLabel;
17 17
@@ -22,10 +22,11 @@ use super::short_label::ShortLabel;
22/// code, like a function or a struct, but this is not strictly required. 22/// code, like a function or a struct, but this is not strictly required.
23#[derive(Debug, Clone, PartialEq, Eq, Hash)] 23#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24pub struct NavigationTarget { 24pub struct NavigationTarget {
25 // FIXME: use FileRange?
25 file_id: FileId, 26 file_id: FileId,
27 full_range: TextRange,
26 name: SmolStr, 28 name: SmolStr,
27 kind: SyntaxKind, 29 kind: SyntaxKind,
28 full_range: TextRange,
29 focus_range: Option<TextRange>, 30 focus_range: Option<TextRange>,
30 container_name: Option<SmolStr>, 31 container_name: Option<SmolStr>,
31 description: Option<String>, 32 description: Option<String>,
@@ -63,6 +64,10 @@ impl NavigationTarget {
63 self.file_id 64 self.file_id
64 } 65 }
65 66
67 pub fn file_range(&self) -> FileRange {
68 FileRange { file_id: self.file_id, range: self.full_range }
69 }
70
66 pub fn full_range(&self) -> TextRange { 71 pub fn full_range(&self) -> TextRange {
67 self.full_range 72 self.full_range
68 } 73 }
diff --git a/crates/ra_ide/src/references.rs b/crates/ra_ide/src/references.rs
index 555ccf295..074284b42 100644
--- a/crates/ra_ide/src/references.rs
+++ b/crates/ra_ide/src/references.rs
@@ -593,6 +593,31 @@ mod tests {
593 check_result(refs, "i BIND_PAT FileId(1) 36..37 Other", &["FileId(1) 51..52 Other Write"]); 593 check_result(refs, "i BIND_PAT FileId(1) 36..37 Other", &["FileId(1) 51..52 Other Write"]);
594 } 594 }
595 595
596 #[test]
597 fn test_find_struct_function_refs_outside_module() {
598 let code = r#"
599 mod foo {
600 pub struct Foo;
601
602 impl Foo {
603 pub fn new<|>() -> Foo {
604 Foo
605 }
606 }
607 }
608
609 fn main() {
610 let _f = foo::Foo::new();
611 }"#;
612
613 let refs = get_all_refs(code);
614 check_result(
615 refs,
616 "new FN_DEF FileId(1) 87..150 94..97 Other",
617 &["FileId(1) 227..230 StructLiteral"],
618 );
619 }
620
596 fn get_all_refs(text: &str) -> ReferenceSearchResult { 621 fn get_all_refs(text: &str) -> ReferenceSearchResult {
597 let (analysis, position) = single_file_with_position(text); 622 let (analysis, position) = single_file_with_position(text);
598 analysis.find_all_refs(position, None).unwrap().unwrap() 623 analysis.find_all_refs(position, None).unwrap().unwrap()
diff --git a/crates/ra_ide/src/snapshots/highlight_strings.html b/crates/ra_ide/src/snapshots/highlight_strings.html
index de06daf72..752b487e8 100644
--- a/crates/ra_ide/src/snapshots/highlight_strings.html
+++ b/crates/ra_ide/src/snapshots/highlight_strings.html
@@ -27,13 +27,13 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
27.keyword.unsafe { color: #BC8383; font-weight: bold; } 27.keyword.unsafe { color: #BC8383; font-weight: bold; }
28.control { font-style: italic; } 28.control { font-style: italic; }
29</style> 29</style>
30<pre><code><span class="macro">macro_rules!</span> println { 30<pre><code><span class="macro">macro_rules!</span> <span class="macro declaration">println</span> {
31 ($($arg:tt)*) =&gt; ({ 31 ($($arg:tt)*) =&gt; ({
32 $<span class="keyword">crate</span>::io::_print($<span class="keyword">crate</span>::format_args_nl!($($arg)*)); 32 $<span class="keyword">crate</span>::io::_print($<span class="keyword">crate</span>::format_args_nl!($($arg)*));
33 }) 33 })
34} 34}
35#[rustc_builtin_macro] 35#[rustc_builtin_macro]
36<span class="macro">macro_rules!</span> format_args_nl { 36<span class="macro">macro_rules!</span> <span class="macro declaration">format_args_nl</span> {
37 ($fmt:expr) =&gt; {{ <span class="comment">/* compiler built-in */</span> }}; 37 ($fmt:expr) =&gt; {{ <span class="comment">/* compiler built-in */</span> }};
38 ($fmt:expr, $($args:tt)*) =&gt; {{ <span class="comment">/* compiler built-in */</span> }}; 38 ($fmt:expr, $($args:tt)*) =&gt; {{ <span class="comment">/* compiler built-in */</span> }};
39} 39}
diff --git a/crates/ra_ide/src/snapshots/highlighting.html b/crates/ra_ide/src/snapshots/highlighting.html
index 4b12fe823..635fe5cf9 100644
--- a/crates/ra_ide/src/snapshots/highlighting.html
+++ b/crates/ra_ide/src/snapshots/highlighting.html
@@ -33,11 +33,23 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
33 <span class="keyword">pub</span> <span class="field declaration">y</span>: <span class="builtin_type">i32</span>, 33 <span class="keyword">pub</span> <span class="field declaration">y</span>: <span class="builtin_type">i32</span>,
34} 34}
35 35
36<span class="keyword">trait</span> <span class="trait declaration">Bar</span> {
37 <span class="keyword">fn</span> <span class="function declaration">bar</span>(&<span class="keyword">self</span>) -&gt; <span class="builtin_type">i32</span>;
38}
39
40<span class="keyword">impl</span> <span class="trait">Bar</span> <span class="keyword">for</span> <span class="struct">Foo</span> {
41 <span class="keyword">fn</span> <span class="function declaration">bar</span>(&<span class="keyword">self</span>) -&gt; <span class="builtin_type">i32</span> {
42 <span class="keyword">self</span>.<span class="field">x</span>
43 }
44}
45
46<span class="keyword">static</span> <span class="keyword">mut</span> <span class="static declaration mutable">STATIC_MUT</span>: <span class="builtin_type">i32</span> = <span class="numeric_literal">0</span>;
47
36<span class="keyword">fn</span> <span class="function declaration">foo</span>&lt;<span class="lifetime declaration">'a</span>, <span class="type_param declaration">T</span>&gt;() -&gt; <span class="type_param">T</span> { 48<span class="keyword">fn</span> <span class="function declaration">foo</span>&lt;<span class="lifetime declaration">'a</span>, <span class="type_param declaration">T</span>&gt;() -&gt; <span class="type_param">T</span> {
37 <span class="function">foo</span>::&lt;<span class="lifetime">'a</span>, <span class="builtin_type">i32</span>&gt;() 49 <span class="function">foo</span>::&lt;<span class="lifetime">'a</span>, <span class="builtin_type">i32</span>&gt;()
38} 50}
39 51
40<span class="macro">macro_rules!</span> def_fn { 52<span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> {
41 ($($tt:tt)*) =&gt; {$($tt)*} 53 ($($tt:tt)*) =&gt; {$($tt)*}
42} 54}
43 55
@@ -56,7 +68,14 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
56 <span class="keyword">let</span> <span class="variable declaration">x</span> = <span class="numeric_literal">92</span>; 68 <span class="keyword">let</span> <span class="variable declaration">x</span> = <span class="numeric_literal">92</span>;
57 <span class="variable mutable">vec</span>.<span class="unresolved_reference">push</span>(<span class="struct">Foo</span> { <span class="field">x</span>, <span class="field">y</span>: <span class="numeric_literal">1</span> }); 69 <span class="variable mutable">vec</span>.<span class="unresolved_reference">push</span>(<span class="struct">Foo</span> { <span class="field">x</span>, <span class="field">y</span>: <span class="numeric_literal">1</span> });
58 } 70 }
59 <span class="keyword unsafe">unsafe</span> { <span class="variable mutable">vec</span>.<span class="unresolved_reference">set_len</span>(<span class="numeric_literal">0</span>); } 71 <span class="keyword unsafe">unsafe</span> {
72 <span class="variable mutable">vec</span>.<span class="unresolved_reference">set_len</span>(<span class="numeric_literal">0</span>);
73 <span class="static mutable">STATIC_MUT</span> = <span class="numeric_literal">1</span>;
74 }
75
76 <span class="keyword control">for</span> <span class="variable declaration">e</span> <span class="keyword control">in</span> <span class="variable mutable">vec</span> {
77 <span class="comment">// Do nothing</span>
78 }
60 79
61 <span class="keyword">let</span> <span class="keyword">mut</span> <span class="variable declaration mutable">x</span> = <span class="numeric_literal">42</span>; 80 <span class="keyword">let</span> <span class="keyword">mut</span> <span class="variable declaration mutable">x</span> = <span class="numeric_literal">42</span>;
62 <span class="keyword">let</span> <span class="variable declaration mutable">y</span> = &<span class="keyword">mut</span> <span class="variable mutable">x</span>; 81 <span class="keyword">let</span> <span class="variable declaration mutable">y</span> = &<span class="keyword">mut</span> <span class="variable mutable">x</span>;
diff --git a/crates/ra_ide/src/syntax_highlighting.rs b/crates/ra_ide/src/syntax_highlighting.rs
index 6658c7bb2..be57eeb0a 100644
--- a/crates/ra_ide/src/syntax_highlighting.rs
+++ b/crates/ra_ide/src/syntax_highlighting.rs
@@ -167,6 +167,19 @@ pub(crate) fn highlight(
167 binding_hash: None, 167 binding_hash: None,
168 }); 168 });
169 } 169 }
170 if let Some(name) = mc.is_macro_rules() {
171 if let Some((highlight, binding_hash)) = highlight_element(
172 &sema,
173 &mut bindings_shadow_count,
174 name.syntax().clone().into(),
175 ) {
176 stack.add(HighlightedRange {
177 range: name.syntax().text_range(),
178 highlight,
179 binding_hash,
180 });
181 }
182 }
170 continue; 183 continue;
171 } 184 }
172 WalkEvent::Leave(Some(mc)) => { 185 WalkEvent::Leave(Some(mc)) => {
@@ -390,12 +403,13 @@ fn highlight_element(
390 T![break] 403 T![break]
391 | T![continue] 404 | T![continue]
392 | T![else] 405 | T![else]
393 | T![for]
394 | T![if] 406 | T![if]
395 | T![loop] 407 | T![loop]
396 | T![match] 408 | T![match]
397 | T![return] 409 | T![return]
398 | T![while] => h | HighlightModifier::ControlFlow, 410 | T![while]
411 | T![in] => h | HighlightModifier::ControlFlow,
412 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
399 T![unsafe] => h | HighlightModifier::Unsafe, 413 T![unsafe] => h | HighlightModifier::Unsafe,
400 _ => h, 414 _ => h,
401 } 415 }
@@ -419,6 +433,13 @@ fn highlight_element(
419 } 433 }
420} 434}
421 435
436fn is_child_of_impl(element: SyntaxElement) -> bool {
437 match element.parent() {
438 Some(e) => e.kind() == IMPL_DEF,
439 _ => false,
440 }
441}
442
422fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight { 443fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
423 match def { 444 match def {
424 Definition::Macro(_) => HighlightTag::Macro, 445 Definition::Macro(_) => HighlightTag::Macro,
@@ -431,10 +452,16 @@ fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
431 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union, 452 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
432 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant, 453 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
433 hir::ModuleDef::Const(_) => HighlightTag::Constant, 454 hir::ModuleDef::Const(_) => HighlightTag::Constant,
434 hir::ModuleDef::Static(_) => HighlightTag::Static,
435 hir::ModuleDef::Trait(_) => HighlightTag::Trait, 455 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
436 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias, 456 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
437 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType, 457 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
458 hir::ModuleDef::Static(s) => {
459 let mut h = Highlight::new(HighlightTag::Static);
460 if s.is_mut(db) {
461 h |= HighlightModifier::Mutable;
462 }
463 return h;
464 }
438 }, 465 },
439 Definition::SelfType(_) => HighlightTag::SelfType, 466 Definition::SelfType(_) => HighlightTag::SelfType,
440 Definition::TypeParam(_) => HighlightTag::TypeParam, 467 Definition::TypeParam(_) => HighlightTag::TypeParam,
diff --git a/crates/ra_ide/src/syntax_highlighting/tests.rs b/crates/ra_ide/src/syntax_highlighting/tests.rs
index d2926ba78..eb43a23da 100644
--- a/crates/ra_ide/src/syntax_highlighting/tests.rs
+++ b/crates/ra_ide/src/syntax_highlighting/tests.rs
@@ -17,6 +17,18 @@ struct Foo {
17 pub y: i32, 17 pub y: i32,
18} 18}
19 19
20trait Bar {
21 fn bar(&self) -> i32;
22}
23
24impl Bar for Foo {
25 fn bar(&self) -> i32 {
26 self.x
27 }
28}
29
30static mut STATIC_MUT: i32 = 0;
31
20fn foo<'a, T>() -> T { 32fn foo<'a, T>() -> T {
21 foo::<'a, i32>() 33 foo::<'a, i32>()
22} 34}
@@ -40,7 +52,14 @@ fn main() {
40 let x = 92; 52 let x = 92;
41 vec.push(Foo { x, y: 1 }); 53 vec.push(Foo { x, y: 1 });
42 } 54 }
43 unsafe { vec.set_len(0); } 55 unsafe {
56 vec.set_len(0);
57 STATIC_MUT = 1;
58 }
59
60 for e in vec {
61 // Do nothing
62 }
44 63
45 let mut x = 42; 64 let mut x = 42;
46 let y = &mut x; 65 let y = &mut x;
diff --git a/crates/ra_ide_db/src/defs.rs b/crates/ra_ide_db/src/defs.rs
index f990e3bb9..60c11178e 100644
--- a/crates/ra_ide_db/src/defs.rs
+++ b/crates/ra_ide_db/src/defs.rs
@@ -6,7 +6,7 @@
6// FIXME: this badly needs rename/rewrite (matklad, 2020-02-06). 6// FIXME: this badly needs rename/rewrite (matklad, 2020-02-06).
7 7
8use hir::{ 8use hir::{
9 Adt, Field, HasVisibility, ImplDef, Local, MacroDef, Module, ModuleDef, Name, PathResolution, 9 Field, HasVisibility, ImplDef, Local, MacroDef, Module, ModuleDef, Name, PathResolution,
10 Semantics, TypeParam, Visibility, 10 Semantics, TypeParam, Visibility,
11}; 11};
12use ra_prof::profile; 12use ra_prof::profile;
@@ -42,18 +42,10 @@ impl Definition {
42 } 42 }
43 43
44 pub fn visibility(&self, db: &RootDatabase) -> Option<Visibility> { 44 pub fn visibility(&self, db: &RootDatabase) -> Option<Visibility> {
45 let module = self.module(db);
46
47 match self { 45 match self {
48 Definition::Macro(_) => None, 46 Definition::Macro(_) => None,
49 Definition::Field(sf) => Some(sf.visibility(db)), 47 Definition::Field(sf) => Some(sf.visibility(db)),
50 Definition::ModuleDef(def) => match def { 48 Definition::ModuleDef(def) => def.definition_visibility(db),
51 ModuleDef::EnumVariant(id) => {
52 let parent = id.parent_enum(db);
53 module?.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)))
54 }
55 _ => module?.visibility_of(db, def),
56 },
57 Definition::SelfType(_) => None, 49 Definition::SelfType(_) => None,
58 Definition::Local(_) => None, 50 Definition::Local(_) => None,
59 Definition::TypeParam(_) => None, 51 Definition::TypeParam(_) => None,
diff --git a/crates/ra_proc_macro_srv/Cargo.toml b/crates/ra_proc_macro_srv/Cargo.toml
index 886e14870..bb3003278 100644
--- a/crates/ra_proc_macro_srv/Cargo.toml
+++ b/crates/ra_proc_macro_srv/Cargo.toml
@@ -18,7 +18,7 @@ memmap = "0.7"
18test_utils = { path = "../test_utils" } 18test_utils = { path = "../test_utils" }
19 19
20[dev-dependencies] 20[dev-dependencies]
21cargo_metadata = "0.9.1" 21cargo_metadata = "0.10.0"
22difference = "2.0.0" 22difference = "2.0.0"
23# used as proc macro test target 23# used as proc macro test target
24serde_derive = "=1.0.106" 24serde_derive = "1.0.106"
diff --git a/crates/ra_proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt b/crates/ra_proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt
index 6776f5231..bc010cfe9 100644
--- a/crates/ra_proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt
+++ b/crates/ra_proc_macro_srv/src/tests/fixtures/test_serialize_proc_macro.txt
@@ -23,23 +23,12 @@ SUBTREE $
23 SUBTREE [] 4294967295 23 SUBTREE [] 4294967295
24 IDENT allow 4294967295 24 IDENT allow 4294967295
25 SUBTREE () 4294967295 25 SUBTREE () 4294967295
26 IDENT unknown_lints 4294967295
27 PUNCH # [alone] 4294967295
28 SUBTREE [] 4294967295
29 IDENT cfg_attr 4294967295
30 SUBTREE () 4294967295
31 IDENT feature 4294967295
32 PUNCH = [alone] 4294967295
33 LITERAL "cargo-clippy" 0
34 PUNCH , [alone] 4294967295
35 IDENT allow 4294967295
36 SUBTREE () 4294967295
37 IDENT useless_attribute 4294967295
38 PUNCH # [alone] 4294967295
39 SUBTREE [] 4294967295
40 IDENT allow 4294967295
41 SUBTREE () 4294967295
42 IDENT rust_2018_idioms 4294967295 26 IDENT rust_2018_idioms 4294967295
27 PUNCH , [alone] 4294967295
28 IDENT clippy 4294967295
29 PUNCH : [joint] 4294967295
30 PUNCH : [alone] 4294967295
31 IDENT useless_attribute 4294967295
43 IDENT extern 4294967295 32 IDENT extern 4294967295
44 IDENT crate 4294967295 33 IDENT crate 4294967295
45 IDENT serde 4294967295 34 IDENT serde 4294967295
diff --git a/crates/ra_proc_macro_srv/src/tests/mod.rs b/crates/ra_proc_macro_srv/src/tests/mod.rs
index 9cf58511c..82cefbb29 100644
--- a/crates/ra_proc_macro_srv/src/tests/mod.rs
+++ b/crates/ra_proc_macro_srv/src/tests/mod.rs
@@ -10,7 +10,7 @@ fn test_derive_serialize_proc_macro() {
10 assert_expand( 10 assert_expand(
11 "serde_derive", 11 "serde_derive",
12 "Serialize", 12 "Serialize",
13 "1.0.106", 13 "1.0",
14 r##"struct Foo {}"##, 14 r##"struct Foo {}"##,
15 include_str!("fixtures/test_serialize_proc_macro.txt"), 15 include_str!("fixtures/test_serialize_proc_macro.txt"),
16 ); 16 );
@@ -21,7 +21,7 @@ fn test_derive_serialize_proc_macro_failed() {
21 assert_expand( 21 assert_expand(
22 "serde_derive", 22 "serde_derive",
23 "Serialize", 23 "Serialize",
24 "1.0.106", 24 "1.0",
25 r##" 25 r##"
26 struct {} 26 struct {}
27"##, 27"##,
@@ -37,7 +37,7 @@ SUBTREE $
37 37
38#[test] 38#[test]
39fn test_derive_proc_macro_list() { 39fn test_derive_proc_macro_list() {
40 let res = list("serde_derive", "1.0.106").join("\n"); 40 let res = list("serde_derive", "1.0").join("\n");
41 41
42 assert_eq_text!( 42 assert_eq_text!(
43 &res, 43 &res,
diff --git a/crates/ra_proc_macro_srv/src/tests/utils.rs b/crates/ra_proc_macro_srv/src/tests/utils.rs
index 646a427c5..84348b5de 100644
--- a/crates/ra_proc_macro_srv/src/tests/utils.rs
+++ b/crates/ra_proc_macro_srv/src/tests/utils.rs
@@ -8,7 +8,7 @@ use std::str::FromStr;
8use test_utils::assert_eq_text; 8use test_utils::assert_eq_text;
9 9
10mod fixtures { 10mod fixtures {
11 use cargo_metadata::{parse_messages, Message}; 11 use cargo_metadata::Message;
12 use std::process::Command; 12 use std::process::Command;
13 13
14 // Use current project metadata to get the proc-macro dylib path 14 // Use current project metadata to get the proc-macro dylib path
@@ -19,7 +19,7 @@ mod fixtures {
19 .unwrap() 19 .unwrap()
20 .stdout; 20 .stdout;
21 21
22 for message in parse_messages(command.as_slice()) { 22 for message in Message::parse_stream(command.as_slice()) {
23 match message.unwrap() { 23 match message.unwrap() {
24 Message::CompilerArtifact(artifact) => { 24 Message::CompilerArtifact(artifact) => {
25 if artifact.target.kind.contains(&"proc-macro".to_string()) { 25 if artifact.target.kind.contains(&"proc-macro".to_string()) {
diff --git a/crates/ra_project_model/Cargo.toml b/crates/ra_project_model/Cargo.toml
index a32a5daab..e4a60f4c0 100644
--- a/crates/ra_project_model/Cargo.toml
+++ b/crates/ra_project_model/Cargo.toml
@@ -11,7 +11,7 @@ doctest = false
11log = "0.4.8" 11log = "0.4.8"
12rustc-hash = "1.1.0" 12rustc-hash = "1.1.0"
13 13
14cargo_metadata = "0.9.1" 14cargo_metadata = "0.10.0"
15 15
16ra_arena = { path = "../ra_arena" } 16ra_arena = { path = "../ra_arena" }
17ra_cfg = { path = "../ra_cfg" } 17ra_cfg = { path = "../ra_cfg" }
diff --git a/crates/ra_project_model/src/cargo_workspace.rs b/crates/ra_project_model/src/cargo_workspace.rs
index 082af4f96..a306ce95f 100644
--- a/crates/ra_project_model/src/cargo_workspace.rs
+++ b/crates/ra_project_model/src/cargo_workspace.rs
@@ -161,7 +161,7 @@ impl CargoWorkspace {
161 meta.current_dir(parent); 161 meta.current_dir(parent);
162 } 162 }
163 if let Some(target) = cargo_features.target.as_ref() { 163 if let Some(target) = cargo_features.target.as_ref() {
164 meta.other_options(&[String::from("--filter-platform"), target.clone()]); 164 meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
165 } 165 }
166 let meta = meta.exec().with_context(|| { 166 let meta = meta.exec().with_context(|| {
167 format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display()) 167 format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())
@@ -304,19 +304,13 @@ pub fn load_extern_resources(
304 304
305 let mut res = ExternResources::default(); 305 let mut res = ExternResources::default();
306 306
307 for message in cargo_metadata::parse_messages(output.stdout.as_slice()) { 307 for message in cargo_metadata::Message::parse_stream(output.stdout.as_slice()) {
308 if let Ok(message) = message { 308 if let Ok(message) = message {
309 match message { 309 match message {
310 Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => { 310 Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => {
311 res.out_dirs.insert(package_id.clone(), out_dir); 311 res.out_dirs.insert(package_id.clone(), out_dir);
312 res.cfgs.insert( 312 res.cfgs.insert(package_id, cfgs);
313 package_id,
314 // FIXME: Current `cargo_metadata` uses `PathBuf` instead of `String`,
315 // change when https://github.com/oli-obk/cargo_metadata/pulls/112 reaches crates.io
316 cfgs.iter().filter_map(|c| c.to_str().map(|s| s.to_owned())).collect(),
317 );
318 } 313 }
319
320 Message::CompilerArtifact(message) => { 314 Message::CompilerArtifact(message) => {
321 if message.target.kind.contains(&"proc-macro".to_string()) { 315 if message.target.kind.contains(&"proc-macro".to_string()) {
322 let package_id = message.package_id; 316 let package_id = message.package_id;
@@ -329,6 +323,8 @@ pub fn load_extern_resources(
329 } 323 }
330 Message::CompilerMessage(_) => (), 324 Message::CompilerMessage(_) => (),
331 Message::Unknown => (), 325 Message::Unknown => (),
326 Message::BuildFinished(_) => {}
327 Message::TextLine(_) => {}
332 } 328 }
333 } 329 }
334 } 330 }
diff --git a/crates/ra_syntax/src/ast/make.rs b/crates/ra_syntax/src/ast/make.rs
index 7b17fef49..12c5228f5 100644
--- a/crates/ra_syntax/src/ast/make.rs
+++ b/crates/ra_syntax/src/ast/make.rs
@@ -300,7 +300,12 @@ pub fn add_pub_crate_modifier(fn_def: ast::FnDef) -> ast::FnDef {
300 300
301fn ast_from_text<N: AstNode>(text: &str) -> N { 301fn ast_from_text<N: AstNode>(text: &str) -> N {
302 let parse = SourceFile::parse(text); 302 let parse = SourceFile::parse(text);
303 let node = parse.tree().syntax().descendants().find_map(N::cast).unwrap(); 303 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
304 Some(it) => it,
305 None => {
306 panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
307 }
308 };
304 let node = node.syntax().clone(); 309 let node = node.syntax().clone();
305 let node = unroot(node); 310 let node = unroot(node);
306 let node = N::cast(node).unwrap(); 311 let node = N::cast(node).unwrap();
diff --git a/crates/ra_text_edit/src/lib.rs b/crates/ra_text_edit/src/lib.rs
index 3409713ff..37f77cc47 100644
--- a/crates/ra_text_edit/src/lib.rs
+++ b/crates/ra_text_edit/src/lib.rs
@@ -75,6 +75,7 @@ impl TextEdit {
75 self.indels.is_empty() 75 self.indels.is_empty()
76 } 76 }
77 77
78 // FXME: impl IntoIter instead
78 pub fn as_indels(&self) -> &[Indel] { 79 pub fn as_indels(&self) -> &[Indel] {
79 &self.indels 80 &self.indels
80 } 81 }
diff --git a/crates/ra_toolchain/src/lib.rs b/crates/ra_toolchain/src/lib.rs
index 3c307a0ea..3d2865e09 100644
--- a/crates/ra_toolchain/src/lib.rs
+++ b/crates/ra_toolchain/src/lib.rs
@@ -53,10 +53,9 @@ fn lookup_in_path(exec: &str) -> bool {
53 let paths = env::var_os("PATH").unwrap_or_default(); 53 let paths = env::var_os("PATH").unwrap_or_default();
54 let mut candidates = env::split_paths(&paths).flat_map(|path| { 54 let mut candidates = env::split_paths(&paths).flat_map(|path| {
55 let candidate = path.join(&exec); 55 let candidate = path.join(&exec);
56 let with_exe = if env::consts::EXE_EXTENSION == "" { 56 let with_exe = match env::consts::EXE_EXTENSION {
57 None 57 "" => None,
58 } else { 58 it => Some(candidate.with_extension(it)),
59 Some(candidate.with_extension(env::consts::EXE_EXTENSION))
60 }; 59 };
61 iter::once(candidate).chain(with_exe) 60 iter::once(candidate).chain(with_exe)
62 }); 61 });
diff --git a/crates/rust-analyzer/src/bin/main.rs b/crates/rust-analyzer/src/bin/main.rs
index 22a84b50c..09908458d 100644
--- a/crates/rust-analyzer/src/bin/main.rs
+++ b/crates/rust-analyzer/src/bin/main.rs
@@ -60,7 +60,7 @@ fn main() -> Result<()> {
60 60
61fn setup_logging() -> Result<()> { 61fn setup_logging() -> Result<()> {
62 std::env::set_var("RUST_BACKTRACE", "short"); 62 std::env::set_var("RUST_BACKTRACE", "short");
63 env_logger::try_init()?; 63 env_logger::try_init_from_env("RA_LOG")?;
64 ra_prof::init(); 64 ra_prof::init();
65 Ok(()) 65 Ok(())
66} 66}
@@ -100,9 +100,8 @@ fn run_server() -> Result<()> {
100 if let Some(value) = &initialize_params.initialization_options { 100 if let Some(value) = &initialize_params.initialization_options {
101 config.update(value); 101 config.update(value);
102 } 102 }
103 if let Some(caps) = &initialize_params.capabilities.text_document { 103 config.update_caps(&initialize_params.capabilities);
104 config.update_caps(caps); 104
105 }
106 config 105 config
107 }; 106 };
108 107
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index ccc38e3bb..53aee833d 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -9,7 +9,7 @@
9 9
10use std::{ffi::OsString, path::PathBuf}; 10use std::{ffi::OsString, path::PathBuf};
11 11
12use lsp_types::TextDocumentClientCapabilities; 12use lsp_types::ClientCapabilities;
13use ra_flycheck::FlycheckConfig; 13use ra_flycheck::FlycheckConfig;
14use ra_ide::{CompletionConfig, InlayHintsConfig}; 14use ra_ide::{CompletionConfig, InlayHintsConfig};
15use ra_project_model::CargoConfig; 15use ra_project_model::CargoConfig;
@@ -70,6 +70,7 @@ pub struct ClientCapsConfig {
70 pub line_folding_only: bool, 70 pub line_folding_only: bool,
71 pub hierarchical_symbols: bool, 71 pub hierarchical_symbols: bool,
72 pub code_action_literals: bool, 72 pub code_action_literals: bool,
73 pub work_done_progress: bool,
73} 74}
74 75
75impl Default for Config { 76impl Default for Config {
@@ -208,30 +209,43 @@ impl Config {
208 } 209 }
209 } 210 }
210 211
211 pub fn update_caps(&mut self, caps: &TextDocumentClientCapabilities) { 212 pub fn update_caps(&mut self, caps: &ClientCapabilities) {
212 if let Some(value) = caps.definition.as_ref().and_then(|it| it.link_support) { 213 if let Some(doc_caps) = caps.text_document.as_ref() {
213 self.client_caps.location_link = value; 214 if let Some(value) = doc_caps.definition.as_ref().and_then(|it| it.link_support) {
214 } 215 self.client_caps.location_link = value;
215 if let Some(value) = caps.folding_range.as_ref().and_then(|it| it.line_folding_only) { 216 }
216 self.client_caps.line_folding_only = value 217 if let Some(value) = doc_caps.folding_range.as_ref().and_then(|it| it.line_folding_only)
217 } 218 {
218 if let Some(value) = 219 self.client_caps.line_folding_only = value
219 caps.document_symbol.as_ref().and_then(|it| it.hierarchical_document_symbol_support) 220 }
220 { 221 if let Some(value) = doc_caps
221 self.client_caps.hierarchical_symbols = value 222 .document_symbol
222 } 223 .as_ref()
223 if let Some(value) = 224 .and_then(|it| it.hierarchical_document_symbol_support)
224 caps.code_action.as_ref().and_then(|it| Some(it.code_action_literal_support.is_some())) 225 {
225 { 226 self.client_caps.hierarchical_symbols = value
226 self.client_caps.code_action_literals = value; 227 }
227 } 228 if let Some(value) = doc_caps
228 self.completion.allow_snippets(false); 229 .code_action
229 if let Some(completion) = &caps.completion { 230 .as_ref()
230 if let Some(completion_item) = &completion.completion_item { 231 .and_then(|it| Some(it.code_action_literal_support.is_some()))
231 if let Some(value) = completion_item.snippet_support { 232 {
232 self.completion.allow_snippets(value); 233 self.client_caps.code_action_literals = value;
234 }
235 self.completion.allow_snippets(false);
236 if let Some(completion) = &doc_caps.completion {
237 if let Some(completion_item) = &completion.completion_item {
238 if let Some(value) = completion_item.snippet_support {
239 self.completion.allow_snippets(value);
240 }
233 } 241 }
234 } 242 }
235 } 243 }
244
245 if let Some(window_caps) = caps.window.as_ref() {
246 if let Some(value) = window_caps.work_done_progress {
247 self.client_caps.work_done_progress = value;
248 }
249 }
236 } 250 }
237} 251}
diff --git a/crates/rust-analyzer/src/conv.rs b/crates/rust-analyzer/src/conv.rs
deleted file mode 100644
index f64c90b5b..000000000
--- a/crates/rust-analyzer/src/conv.rs
+++ /dev/null
@@ -1,726 +0,0 @@
1//! Convenience module responsible for translating between rust-analyzer's types
2//! and LSP types.
3
4use lsp_types::{
5 self, CreateFile, DiagnosticSeverity, DocumentChangeOperation, DocumentChanges, Documentation,
6 Location, LocationLink, MarkupContent, MarkupKind, ParameterInformation, ParameterLabel,
7 Position, Range, RenameFile, ResourceOp, SemanticTokenModifier, SemanticTokenType,
8 SignatureInformation, SymbolKind, TextDocumentEdit, TextDocumentIdentifier, TextDocumentItem,
9 TextDocumentPositionParams, Url, VersionedTextDocumentIdentifier, WorkspaceEdit,
10};
11use ra_ide::{
12 translate_offset_with_edit, CompletionItem, CompletionItemKind, FileId, FilePosition,
13 FileRange, FileSystemEdit, Fold, FoldKind, Highlight, HighlightModifier, HighlightTag,
14 InlayHint, InlayKind, InsertTextFormat, LineCol, LineIndex, NavigationTarget, RangeInfo,
15 ReferenceAccess, Severity, SourceChange, SourceFileEdit,
16};
17use ra_syntax::{SyntaxKind, TextRange, TextSize};
18use ra_text_edit::{Indel, TextEdit};
19use ra_vfs::LineEndings;
20
21use crate::{
22 req,
23 semantic_tokens::{self, ModifierSet, CONSTANT, CONTROL_FLOW, MUTABLE, UNSAFE},
24 world::WorldSnapshot,
25 Result,
26};
27use semantic_tokens::{
28 ATTRIBUTE, BUILTIN_TYPE, ENUM_MEMBER, FORMAT_SPECIFIER, LIFETIME, TYPE_ALIAS, UNION,
29 UNRESOLVED_REFERENCE,
30};
31
32pub trait Conv {
33 type Output;
34 fn conv(self) -> Self::Output;
35}
36
37pub trait ConvWith<CTX> {
38 type Output;
39 fn conv_with(self, ctx: CTX) -> Self::Output;
40}
41
42pub trait TryConvWith<CTX> {
43 type Output;
44 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output>;
45}
46
47impl Conv for SyntaxKind {
48 type Output = SymbolKind;
49
50 fn conv(self) -> <Self as Conv>::Output {
51 match self {
52 SyntaxKind::FN_DEF => SymbolKind::Function,
53 SyntaxKind::STRUCT_DEF => SymbolKind::Struct,
54 SyntaxKind::ENUM_DEF => SymbolKind::Enum,
55 SyntaxKind::ENUM_VARIANT => SymbolKind::EnumMember,
56 SyntaxKind::TRAIT_DEF => SymbolKind::Interface,
57 SyntaxKind::MACRO_CALL => SymbolKind::Function,
58 SyntaxKind::MODULE => SymbolKind::Module,
59 SyntaxKind::TYPE_ALIAS_DEF => SymbolKind::TypeParameter,
60 SyntaxKind::RECORD_FIELD_DEF => SymbolKind::Field,
61 SyntaxKind::STATIC_DEF => SymbolKind::Constant,
62 SyntaxKind::CONST_DEF => SymbolKind::Constant,
63 SyntaxKind::IMPL_DEF => SymbolKind::Object,
64 _ => SymbolKind::Variable,
65 }
66 }
67}
68
69impl Conv for ReferenceAccess {
70 type Output = ::lsp_types::DocumentHighlightKind;
71
72 fn conv(self) -> Self::Output {
73 use lsp_types::DocumentHighlightKind;
74 match self {
75 ReferenceAccess::Read => DocumentHighlightKind::Read,
76 ReferenceAccess::Write => DocumentHighlightKind::Write,
77 }
78 }
79}
80
81impl Conv for CompletionItemKind {
82 type Output = ::lsp_types::CompletionItemKind;
83
84 fn conv(self) -> <Self as Conv>::Output {
85 use lsp_types::CompletionItemKind::*;
86 match self {
87 CompletionItemKind::Keyword => Keyword,
88 CompletionItemKind::Snippet => Snippet,
89 CompletionItemKind::Module => Module,
90 CompletionItemKind::Function => Function,
91 CompletionItemKind::Struct => Struct,
92 CompletionItemKind::Enum => Enum,
93 CompletionItemKind::EnumVariant => EnumMember,
94 CompletionItemKind::BuiltinType => Struct,
95 CompletionItemKind::Binding => Variable,
96 CompletionItemKind::Field => Field,
97 CompletionItemKind::Trait => Interface,
98 CompletionItemKind::TypeAlias => Struct,
99 CompletionItemKind::Const => Constant,
100 CompletionItemKind::Static => Value,
101 CompletionItemKind::Method => Method,
102 CompletionItemKind::TypeParam => TypeParameter,
103 CompletionItemKind::Macro => Method,
104 CompletionItemKind::Attribute => EnumMember,
105 }
106 }
107}
108
109impl Conv for Severity {
110 type Output = DiagnosticSeverity;
111 fn conv(self) -> DiagnosticSeverity {
112 match self {
113 Severity::Error => DiagnosticSeverity::Error,
114 Severity::WeakWarning => DiagnosticSeverity::Hint,
115 }
116 }
117}
118
119impl ConvWith<(&LineIndex, LineEndings)> for CompletionItem {
120 type Output = ::lsp_types::CompletionItem;
121
122 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> ::lsp_types::CompletionItem {
123 let mut additional_text_edits = Vec::new();
124 let mut text_edit = None;
125 // LSP does not allow arbitrary edits in completion, so we have to do a
126 // non-trivial mapping here.
127 for indel in self.text_edit().as_indels() {
128 if indel.delete.contains_range(self.source_range()) {
129 text_edit = Some(if indel.delete == self.source_range() {
130 indel.conv_with((ctx.0, ctx.1))
131 } else {
132 assert!(self.source_range().end() == indel.delete.end());
133 let range1 = TextRange::new(indel.delete.start(), self.source_range().start());
134 let range2 = self.source_range();
135 let edit1 = Indel::replace(range1, String::new());
136 let edit2 = Indel::replace(range2, indel.insert.clone());
137 additional_text_edits.push(edit1.conv_with((ctx.0, ctx.1)));
138 edit2.conv_with((ctx.0, ctx.1))
139 })
140 } else {
141 assert!(self.source_range().intersect(indel.delete).is_none());
142 additional_text_edits.push(indel.conv_with((ctx.0, ctx.1)));
143 }
144 }
145 let text_edit = text_edit.unwrap();
146
147 let mut res = lsp_types::CompletionItem {
148 label: self.label().to_string(),
149 detail: self.detail().map(|it| it.to_string()),
150 filter_text: Some(self.lookup().to_string()),
151 kind: self.kind().map(|it| it.conv()),
152 text_edit: Some(text_edit.into()),
153 additional_text_edits: Some(additional_text_edits),
154 documentation: self.documentation().map(|it| it.conv()),
155 deprecated: Some(self.deprecated()),
156 command: if self.trigger_call_info() {
157 let cmd = lsp_types::Command {
158 title: "triggerParameterHints".into(),
159 command: "editor.action.triggerParameterHints".into(),
160 arguments: None,
161 };
162 Some(cmd)
163 } else {
164 None
165 },
166 ..Default::default()
167 };
168
169 if self.score().is_some() {
170 res.preselect = Some(true)
171 }
172
173 if self.deprecated() {
174 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
175 }
176
177 res.insert_text_format = Some(match self.insert_text_format() {
178 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
179 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
180 });
181
182 res
183 }
184}
185
186impl ConvWith<&LineIndex> for Position {
187 type Output = TextSize;
188
189 fn conv_with(self, line_index: &LineIndex) -> TextSize {
190 let line_col = LineCol { line: self.line as u32, col_utf16: self.character as u32 };
191 line_index.offset(line_col)
192 }
193}
194
195impl ConvWith<&LineIndex> for TextSize {
196 type Output = Position;
197
198 fn conv_with(self, line_index: &LineIndex) -> Position {
199 let line_col = line_index.line_col(self);
200 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16))
201 }
202}
203
204impl ConvWith<&LineIndex> for TextRange {
205 type Output = Range;
206
207 fn conv_with(self, line_index: &LineIndex) -> Range {
208 Range::new(self.start().conv_with(line_index), self.end().conv_with(line_index))
209 }
210}
211
212impl ConvWith<&LineIndex> for Range {
213 type Output = TextRange;
214
215 fn conv_with(self, line_index: &LineIndex) -> TextRange {
216 TextRange::new(self.start.conv_with(line_index), self.end.conv_with(line_index))
217 }
218}
219
220impl Conv for ra_ide::Documentation {
221 type Output = lsp_types::Documentation;
222 fn conv(self) -> Documentation {
223 Documentation::MarkupContent(MarkupContent {
224 kind: MarkupKind::Markdown,
225 value: crate::markdown::format_docs(self.as_str()),
226 })
227 }
228}
229
230impl ConvWith<bool> for ra_ide::FunctionSignature {
231 type Output = lsp_types::SignatureInformation;
232 fn conv_with(self, concise: bool) -> Self::Output {
233 let (label, documentation, params) = if concise {
234 let mut params = self.parameters;
235 if self.has_self_param {
236 params.remove(0);
237 }
238 (params.join(", "), None, params)
239 } else {
240 (self.to_string(), self.doc.map(|it| it.conv()), self.parameters)
241 };
242
243 let parameters: Vec<ParameterInformation> = params
244 .into_iter()
245 .map(|param| ParameterInformation {
246 label: ParameterLabel::Simple(param),
247 documentation: None,
248 })
249 .collect();
250
251 SignatureInformation { label, documentation, parameters: Some(parameters) }
252 }
253}
254
255impl ConvWith<(&LineIndex, LineEndings)> for TextEdit {
256 type Output = Vec<lsp_types::TextEdit>;
257
258 fn conv_with(self, ctx: (&LineIndex, LineEndings)) -> Vec<lsp_types::TextEdit> {
259 self.as_indels().iter().map_conv_with(ctx).collect()
260 }
261}
262
263impl ConvWith<(&LineIndex, LineEndings)> for &Indel {
264 type Output = lsp_types::TextEdit;
265
266 fn conv_with(
267 self,
268 (line_index, line_endings): (&LineIndex, LineEndings),
269 ) -> lsp_types::TextEdit {
270 let mut new_text = self.insert.clone();
271 if line_endings == LineEndings::Dos {
272 new_text = new_text.replace('\n', "\r\n");
273 }
274 lsp_types::TextEdit { range: self.delete.conv_with(line_index), new_text }
275 }
276}
277
278pub(crate) struct FoldConvCtx<'a> {
279 pub(crate) text: &'a str,
280 pub(crate) line_index: &'a LineIndex,
281 pub(crate) line_folding_only: bool,
282}
283
284impl ConvWith<&FoldConvCtx<'_>> for Fold {
285 type Output = lsp_types::FoldingRange;
286
287 fn conv_with(self, ctx: &FoldConvCtx) -> lsp_types::FoldingRange {
288 let kind = match self.kind {
289 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
290 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
291 FoldKind::Mods => None,
292 FoldKind::Block => None,
293 };
294
295 let range = self.range.conv_with(&ctx.line_index);
296
297 if ctx.line_folding_only {
298 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
299 // even if it contains text not in the folding range. To prevent that we exclude
300 // range.end.line from the folding region if there is more text after range.end
301 // on the same line.
302 let has_more_text_on_end_line = ctx.text
303 [TextRange::new(self.range.end(), TextSize::of(ctx.text))]
304 .chars()
305 .take_while(|it| *it != '\n')
306 .any(|it| !it.is_whitespace());
307
308 let end_line = if has_more_text_on_end_line {
309 range.end.line.saturating_sub(1)
310 } else {
311 range.end.line
312 };
313
314 lsp_types::FoldingRange {
315 start_line: range.start.line,
316 start_character: None,
317 end_line,
318 end_character: None,
319 kind,
320 }
321 } else {
322 lsp_types::FoldingRange {
323 start_line: range.start.line,
324 start_character: Some(range.start.character),
325 end_line: range.end.line,
326 end_character: Some(range.end.character),
327 kind,
328 }
329 }
330 }
331}
332
333impl ConvWith<&LineIndex> for InlayHint {
334 type Output = req::InlayHint;
335 fn conv_with(self, line_index: &LineIndex) -> Self::Output {
336 req::InlayHint {
337 label: self.label.to_string(),
338 range: self.range.conv_with(line_index),
339 kind: match self.kind {
340 InlayKind::ParameterHint => req::InlayKind::ParameterHint,
341 InlayKind::TypeHint => req::InlayKind::TypeHint,
342 InlayKind::ChainingHint => req::InlayKind::ChainingHint,
343 },
344 }
345 }
346}
347
348impl Conv for Highlight {
349 type Output = (u32, u32);
350
351 fn conv(self) -> Self::Output {
352 let mut mods = ModifierSet::default();
353 let type_ = match self.tag {
354 HighlightTag::Struct => SemanticTokenType::STRUCT,
355 HighlightTag::Enum => SemanticTokenType::ENUM,
356 HighlightTag::Union => UNION,
357 HighlightTag::TypeAlias => TYPE_ALIAS,
358 HighlightTag::Trait => SemanticTokenType::INTERFACE,
359 HighlightTag::BuiltinType => BUILTIN_TYPE,
360 HighlightTag::SelfType => SemanticTokenType::TYPE,
361 HighlightTag::Field => SemanticTokenType::MEMBER,
362 HighlightTag::Function => SemanticTokenType::FUNCTION,
363 HighlightTag::Module => SemanticTokenType::NAMESPACE,
364 HighlightTag::Constant => {
365 mods |= CONSTANT;
366 mods |= SemanticTokenModifier::STATIC;
367 SemanticTokenType::VARIABLE
368 }
369 HighlightTag::Static => {
370 mods |= SemanticTokenModifier::STATIC;
371 SemanticTokenType::VARIABLE
372 }
373 HighlightTag::EnumVariant => ENUM_MEMBER,
374 HighlightTag::Macro => SemanticTokenType::MACRO,
375 HighlightTag::Local => SemanticTokenType::VARIABLE,
376 HighlightTag::TypeParam => SemanticTokenType::TYPE_PARAMETER,
377 HighlightTag::Lifetime => LIFETIME,
378 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => SemanticTokenType::NUMBER,
379 HighlightTag::CharLiteral | HighlightTag::StringLiteral => SemanticTokenType::STRING,
380 HighlightTag::Comment => SemanticTokenType::COMMENT,
381 HighlightTag::Attribute => ATTRIBUTE,
382 HighlightTag::Keyword => SemanticTokenType::KEYWORD,
383 HighlightTag::UnresolvedReference => UNRESOLVED_REFERENCE,
384 HighlightTag::FormatSpecifier => FORMAT_SPECIFIER,
385 };
386
387 for modifier in self.modifiers.iter() {
388 let modifier = match modifier {
389 HighlightModifier::Definition => SemanticTokenModifier::DECLARATION,
390 HighlightModifier::ControlFlow => CONTROL_FLOW,
391 HighlightModifier::Mutable => MUTABLE,
392 HighlightModifier::Unsafe => UNSAFE,
393 };
394 mods |= modifier;
395 }
396
397 (semantic_tokens::type_index(type_), mods.0)
398 }
399}
400
401impl<T: ConvWith<CTX>, CTX> ConvWith<CTX> for Option<T> {
402 type Output = Option<T::Output>;
403
404 fn conv_with(self, ctx: CTX) -> Self::Output {
405 self.map(|x| ConvWith::conv_with(x, ctx))
406 }
407}
408
409impl TryConvWith<&WorldSnapshot> for &Url {
410 type Output = FileId;
411 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
412 world.uri_to_file_id(self)
413 }
414}
415
416impl TryConvWith<&WorldSnapshot> for FileId {
417 type Output = Url;
418 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Url> {
419 world.file_id_to_uri(self)
420 }
421}
422
423impl TryConvWith<&WorldSnapshot> for &TextDocumentItem {
424 type Output = FileId;
425 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
426 self.uri.try_conv_with(world)
427 }
428}
429
430impl TryConvWith<&WorldSnapshot> for &VersionedTextDocumentIdentifier {
431 type Output = FileId;
432 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
433 self.uri.try_conv_with(world)
434 }
435}
436
437impl TryConvWith<&WorldSnapshot> for &TextDocumentIdentifier {
438 type Output = FileId;
439 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileId> {
440 world.uri_to_file_id(&self.uri)
441 }
442}
443
444impl TryConvWith<&WorldSnapshot> for &TextDocumentPositionParams {
445 type Output = FilePosition;
446 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FilePosition> {
447 let file_id = self.text_document.try_conv_with(world)?;
448 let line_index = world.analysis().file_line_index(file_id)?;
449 let offset = self.position.conv_with(&line_index);
450 Ok(FilePosition { file_id, offset })
451 }
452}
453
454impl TryConvWith<&WorldSnapshot> for (&TextDocumentIdentifier, Range) {
455 type Output = FileRange;
456 fn try_conv_with(self, world: &WorldSnapshot) -> Result<FileRange> {
457 let file_id = self.0.try_conv_with(world)?;
458 let line_index = world.analysis().file_line_index(file_id)?;
459 let range = self.1.conv_with(&line_index);
460 Ok(FileRange { file_id, range })
461 }
462}
463
464impl<T: TryConvWith<CTX>, CTX: Copy> TryConvWith<CTX> for Vec<T> {
465 type Output = Vec<<T as TryConvWith<CTX>>::Output>;
466 fn try_conv_with(self, ctx: CTX) -> Result<Self::Output> {
467 let mut res = Vec::with_capacity(self.len());
468 for item in self {
469 res.push(item.try_conv_with(ctx)?);
470 }
471 Ok(res)
472 }
473}
474
475impl TryConvWith<&WorldSnapshot> for SourceChange {
476 type Output = req::SourceChange;
477 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::SourceChange> {
478 let cursor_position = match self.cursor_position {
479 None => None,
480 Some(pos) => {
481 let line_index = world.analysis().file_line_index(pos.file_id)?;
482 let edit = self
483 .source_file_edits
484 .iter()
485 .find(|it| it.file_id == pos.file_id)
486 .map(|it| &it.edit);
487 let line_col = match edit {
488 Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
489 None => line_index.line_col(pos.offset),
490 };
491 let position =
492 Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
493 Some(TextDocumentPositionParams {
494 text_document: TextDocumentIdentifier::new(pos.file_id.try_conv_with(world)?),
495 position,
496 })
497 }
498 };
499 let mut document_changes: Vec<DocumentChangeOperation> = Vec::new();
500 for resource_op in self.file_system_edits.try_conv_with(world)? {
501 document_changes.push(DocumentChangeOperation::Op(resource_op));
502 }
503 for text_document_edit in self.source_file_edits.try_conv_with(world)? {
504 document_changes.push(DocumentChangeOperation::Edit(text_document_edit));
505 }
506 let workspace_edit = WorkspaceEdit {
507 changes: None,
508 document_changes: Some(DocumentChanges::Operations(document_changes)),
509 };
510 Ok(req::SourceChange { label: self.label, workspace_edit, cursor_position })
511 }
512}
513
514impl TryConvWith<&WorldSnapshot> for SourceFileEdit {
515 type Output = TextDocumentEdit;
516 fn try_conv_with(self, world: &WorldSnapshot) -> Result<TextDocumentEdit> {
517 let text_document = VersionedTextDocumentIdentifier {
518 uri: self.file_id.try_conv_with(world)?,
519 version: None,
520 };
521 let line_index = world.analysis().file_line_index(self.file_id)?;
522 let line_endings = world.file_line_endings(self.file_id);
523 let edits =
524 self.edit.as_indels().iter().map_conv_with((&line_index, line_endings)).collect();
525 Ok(TextDocumentEdit { text_document, edits })
526 }
527}
528
529impl TryConvWith<&WorldSnapshot> for FileSystemEdit {
530 type Output = ResourceOp;
531 fn try_conv_with(self, world: &WorldSnapshot) -> Result<ResourceOp> {
532 let res = match self {
533 FileSystemEdit::CreateFile { source_root, path } => {
534 let uri = world.path_to_uri(source_root, &path)?;
535 ResourceOp::Create(CreateFile { uri, options: None })
536 }
537 FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
538 let old_uri = world.file_id_to_uri(src)?;
539 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
540 ResourceOp::Rename(RenameFile { old_uri, new_uri, options: None })
541 }
542 };
543 Ok(res)
544 }
545}
546
547impl TryConvWith<&WorldSnapshot> for &NavigationTarget {
548 type Output = Location;
549 fn try_conv_with(self, world: &WorldSnapshot) -> Result<Location> {
550 let line_index = world.analysis().file_line_index(self.file_id())?;
551 let range = self.range();
552 to_location(self.file_id(), range, &world, &line_index)
553 }
554}
555
556impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<NavigationTarget>) {
557 type Output = LocationLink;
558 fn try_conv_with(self, world: &WorldSnapshot) -> Result<LocationLink> {
559 let (src_file_id, target) = self;
560
561 let target_uri = target.info.file_id().try_conv_with(world)?;
562 let src_line_index = world.analysis().file_line_index(src_file_id)?;
563 let tgt_line_index = world.analysis().file_line_index(target.info.file_id())?;
564
565 let target_range = target.info.full_range().conv_with(&tgt_line_index);
566
567 let target_selection_range = target
568 .info
569 .focus_range()
570 .map(|it| it.conv_with(&tgt_line_index))
571 .unwrap_or(target_range);
572
573 let res = LocationLink {
574 origin_selection_range: Some(target.range.conv_with(&src_line_index)),
575 target_uri,
576 target_range,
577 target_selection_range,
578 };
579 Ok(res)
580 }
581}
582
583impl TryConvWith<&WorldSnapshot> for (FileId, RangeInfo<Vec<NavigationTarget>>) {
584 type Output = req::GotoDefinitionResponse;
585 fn try_conv_with(self, world: &WorldSnapshot) -> Result<req::GotoTypeDefinitionResponse> {
586 let (file_id, RangeInfo { range, info: navs }) = self;
587 let links = navs
588 .into_iter()
589 .map(|nav| (file_id, RangeInfo::new(range, nav)))
590 .try_conv_with_to_vec(world)?;
591 if world.config.client_caps.location_link {
592 Ok(links.into())
593 } else {
594 let locations: Vec<Location> = links
595 .into_iter()
596 .map(|link| Location { uri: link.target_uri, range: link.target_selection_range })
597 .collect();
598 Ok(locations.into())
599 }
600 }
601}
602
603pub fn to_call_hierarchy_item(
604 file_id: FileId,
605 range: TextRange,
606 world: &WorldSnapshot,
607 line_index: &LineIndex,
608 nav: NavigationTarget,
609) -> Result<lsp_types::CallHierarchyItem> {
610 Ok(lsp_types::CallHierarchyItem {
611 name: nav.name().to_string(),
612 kind: nav.kind().conv(),
613 tags: None,
614 detail: nav.description().map(|it| it.to_string()),
615 uri: file_id.try_conv_with(&world)?,
616 range: nav.range().conv_with(&line_index),
617 selection_range: range.conv_with(&line_index),
618 })
619}
620
621pub fn to_location(
622 file_id: FileId,
623 range: TextRange,
624 world: &WorldSnapshot,
625 line_index: &LineIndex,
626) -> Result<Location> {
627 let url = file_id.try_conv_with(world)?;
628 let loc = Location::new(url, range.conv_with(line_index));
629 Ok(loc)
630}
631
632pub trait MapConvWith<CTX>: Sized {
633 type Output;
634
635 fn map_conv_with(self, ctx: CTX) -> ConvWithIter<Self, CTX> {
636 ConvWithIter { iter: self, ctx }
637 }
638}
639
640impl<CTX, I> MapConvWith<CTX> for I
641where
642 I: Iterator,
643 I::Item: ConvWith<CTX>,
644{
645 type Output = <I::Item as ConvWith<CTX>>::Output;
646}
647
648pub struct ConvWithIter<I, CTX> {
649 iter: I,
650 ctx: CTX,
651}
652
653impl<I, CTX> Iterator for ConvWithIter<I, CTX>
654where
655 I: Iterator,
656 I::Item: ConvWith<CTX>,
657 CTX: Copy,
658{
659 type Item = <I::Item as ConvWith<CTX>>::Output;
660
661 fn next(&mut self) -> Option<Self::Item> {
662 self.iter.next().map(|item| item.conv_with(self.ctx))
663 }
664}
665
666pub trait TryConvWithToVec<CTX>: Sized {
667 type Output;
668
669 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>>;
670}
671
672impl<I, CTX> TryConvWithToVec<CTX> for I
673where
674 I: Iterator,
675 I::Item: TryConvWith<CTX>,
676 CTX: Copy,
677{
678 type Output = <I::Item as TryConvWith<CTX>>::Output;
679
680 fn try_conv_with_to_vec(self, ctx: CTX) -> Result<Vec<Self::Output>> {
681 self.map(|it| it.try_conv_with(ctx)).collect()
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688 use test_utils::extract_ranges;
689
690 #[test]
691 fn conv_fold_line_folding_only_fixup() {
692 let text = r#"<fold>mod a;
693mod b;
694mod c;</fold>
695
696fn main() <fold>{
697 if cond <fold>{
698 a::do_a();
699 }</fold> else <fold>{
700 b::do_b();
701 }</fold>
702}</fold>"#;
703
704 let (ranges, text) = extract_ranges(text, "fold");
705 assert_eq!(ranges.len(), 4);
706 let folds = vec![
707 Fold { range: ranges[0], kind: FoldKind::Mods },
708 Fold { range: ranges[1], kind: FoldKind::Block },
709 Fold { range: ranges[2], kind: FoldKind::Block },
710 Fold { range: ranges[3], kind: FoldKind::Block },
711 ];
712
713 let line_index = LineIndex::new(&text);
714 let ctx = FoldConvCtx { text: &text, line_index: &line_index, line_folding_only: true };
715 let converted: Vec<_> = folds.into_iter().map_conv_with(&ctx).collect();
716
717 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
718 assert_eq!(converted.len(), expected_lines.len());
719 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
720 assert_eq!(folding_range.start_line, *start_line);
721 assert_eq!(folding_range.start_character, None);
722 assert_eq!(folding_range.end_line, *end_line);
723 assert_eq!(folding_range.end_character, None);
724 }
725 }
726}
diff --git a/crates/rust-analyzer/src/from_proto.rs b/crates/rust-analyzer/src/from_proto.rs
new file mode 100644
index 000000000..4bb16a496
--- /dev/null
+++ b/crates/rust-analyzer/src/from_proto.rs
@@ -0,0 +1,42 @@
1//! Conversion lsp_types types to rust-analyzer specific ones.
2use ra_db::{FileId, FilePosition, FileRange};
3use ra_ide::{LineCol, LineIndex};
4use ra_syntax::{TextRange, TextSize};
5
6use crate::{world::WorldSnapshot, Result};
7
8pub(crate) fn offset(line_index: &LineIndex, position: lsp_types::Position) -> TextSize {
9 let line_col = LineCol { line: position.line as u32, col_utf16: position.character as u32 };
10 line_index.offset(line_col)
11}
12
13pub(crate) fn text_range(line_index: &LineIndex, range: lsp_types::Range) -> TextRange {
14 let start = offset(line_index, range.start);
15 let end = offset(line_index, range.end);
16 TextRange::new(start, end)
17}
18
19pub(crate) fn file_id(world: &WorldSnapshot, url: &lsp_types::Url) -> Result<FileId> {
20 world.uri_to_file_id(url)
21}
22
23pub(crate) fn file_position(
24 world: &WorldSnapshot,
25 tdpp: lsp_types::TextDocumentPositionParams,
26) -> Result<FilePosition> {
27 let file_id = file_id(world, &tdpp.text_document.uri)?;
28 let line_index = world.analysis().file_line_index(file_id)?;
29 let offset = offset(&*line_index, tdpp.position);
30 Ok(FilePosition { file_id, offset })
31}
32
33pub(crate) fn file_range(
34 world: &WorldSnapshot,
35 text_document_identifier: lsp_types::TextDocumentIdentifier,
36 range: lsp_types::Range,
37) -> Result<FileRange> {
38 let file_id = file_id(world, &text_document_identifier.uri)?;
39 let line_index = world.analysis().file_line_index(file_id)?;
40 let range = text_range(&line_index, range);
41 Ok(FileRange { file_id, range })
42}
diff --git a/crates/rust-analyzer/src/lib.rs b/crates/rust-analyzer/src/lib.rs
index 036bf62a7..57d0e9218 100644
--- a/crates/rust-analyzer/src/lib.rs
+++ b/crates/rust-analyzer/src/lib.rs
@@ -20,10 +20,11 @@ macro_rules! eprintln {
20mod vfs_glob; 20mod vfs_glob;
21mod caps; 21mod caps;
22mod cargo_target_spec; 22mod cargo_target_spec;
23mod conv; 23mod to_proto;
24mod from_proto;
24mod main_loop; 25mod main_loop;
25mod markdown; 26mod markdown;
26pub mod req; 27pub mod lsp_ext;
27pub mod config; 28pub mod config;
28mod world; 29mod world;
29mod diagnostics; 30mod diagnostics;
diff --git a/crates/rust-analyzer/src/req.rs b/crates/rust-analyzer/src/lsp_ext.rs
index 0dae6bad4..313a8c769 100644
--- a/crates/rust-analyzer/src/req.rs
+++ b/crates/rust-analyzer/src/lsp_ext.rs
@@ -1,25 +1,12 @@
1//! Defines `rust-analyzer` specific custom messages. 1//! rust-analyzer extensions to the LSP.
2 2
3use std::path::PathBuf;
4
5use lsp_types::request::Request;
3use lsp_types::{Location, Position, Range, TextDocumentIdentifier}; 6use lsp_types::{Location, Position, Range, TextDocumentIdentifier};
4use rustc_hash::FxHashMap; 7use rustc_hash::FxHashMap;
5use serde::{Deserialize, Serialize}; 8use serde::{Deserialize, Serialize};
6 9
7pub use lsp_types::{
8 notification::*, request::*, ApplyWorkspaceEditParams, CodeActionParams, CodeLens,
9 CodeLensParams, CompletionParams, CompletionResponse, ConfigurationItem, ConfigurationParams,
10 DiagnosticTag, DidChangeConfigurationParams, DidChangeWatchedFilesParams,
11 DidChangeWatchedFilesRegistrationOptions, DocumentHighlightParams,
12 DocumentOnTypeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse,
13 FileSystemWatcher, GotoDefinitionParams, GotoDefinitionResponse, Hover, HoverParams,
14 InitializeResult, MessageType, PartialResultParams, ProgressParams, ProgressParamsValue,
15 ProgressToken, PublishDiagnosticsParams, ReferenceParams, Registration, RegistrationParams,
16 SelectionRange, SelectionRangeParams, SemanticTokensParams, SemanticTokensRangeParams,
17 SemanticTokensRangeResult, SemanticTokensResult, ServerCapabilities, ShowMessageParams,
18 SignatureHelp, SignatureHelpParams, SymbolKind, TextDocumentEdit, TextDocumentPositionParams,
19 TextEdit, WorkDoneProgressParams, WorkspaceEdit, WorkspaceSymbolParams,
20};
21use std::path::PathBuf;
22
23pub enum AnalyzerStatus {} 10pub enum AnalyzerStatus {}
24 11
25impl Request for AnalyzerStatus { 12impl Request for AnalyzerStatus {
@@ -91,7 +78,7 @@ pub struct FindMatchingBraceParams {
91pub enum ParentModule {} 78pub enum ParentModule {}
92 79
93impl Request for ParentModule { 80impl Request for ParentModule {
94 type Params = TextDocumentPositionParams; 81 type Params = lsp_types::TextDocumentPositionParams;
95 type Result = Vec<Location>; 82 type Result = Vec<Location>;
96 const METHOD: &'static str = "rust-analyzer/parentModule"; 83 const METHOD: &'static str = "rust-analyzer/parentModule";
97} 84}
@@ -114,7 +101,7 @@ pub struct JoinLinesParams {
114pub enum OnEnter {} 101pub enum OnEnter {}
115 102
116impl Request for OnEnter { 103impl Request for OnEnter {
117 type Params = TextDocumentPositionParams; 104 type Params = lsp_types::TextDocumentPositionParams;
118 type Result = Option<SourceChange>; 105 type Result = Option<SourceChange>;
119 const METHOD: &'static str = "rust-analyzer/onEnter"; 106 const METHOD: &'static str = "rust-analyzer/onEnter";
120} 107}
@@ -150,8 +137,8 @@ pub struct Runnable {
150#[serde(rename_all = "camelCase")] 137#[serde(rename_all = "camelCase")]
151pub struct SourceChange { 138pub struct SourceChange {
152 pub label: String, 139 pub label: String,
153 pub workspace_edit: WorkspaceEdit, 140 pub workspace_edit: lsp_types::WorkspaceEdit,
154 pub cursor_position: Option<TextDocumentPositionParams>, 141 pub cursor_position: Option<lsp_types::TextDocumentPositionParams>,
155} 142}
156 143
157pub enum InlayHints {} 144pub enum InlayHints {}
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index 17b0b95b9..13d305b97 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -37,13 +37,12 @@ use threadpool::ThreadPool;
37 37
38use crate::{ 38use crate::{
39 config::{Config, FilesWatcher}, 39 config::{Config, FilesWatcher},
40 conv::{ConvWith, TryConvWith},
41 diagnostics::DiagnosticTask, 40 diagnostics::DiagnosticTask,
41 from_proto, lsp_ext,
42 main_loop::{ 42 main_loop::{
43 pending_requests::{PendingRequest, PendingRequests}, 43 pending_requests::{PendingRequest, PendingRequests},
44 subscriptions::Subscriptions, 44 subscriptions::Subscriptions,
45 }, 45 },
46 req,
47 world::{WorldSnapshot, WorldState}, 46 world::{WorldSnapshot, WorldState},
48 Result, 47 Result,
49}; 48};
@@ -104,7 +103,7 @@ pub fn main_loop(ws_roots: Vec<PathBuf>, config: Config, connection: Connection)
104 103
105 if project_roots.is_empty() && config.notifications.cargo_toml_not_found { 104 if project_roots.is_empty() && config.notifications.cargo_toml_not_found {
106 show_message( 105 show_message(
107 req::MessageType::Error, 106 lsp_types::MessageType::Error,
108 format!( 107 format!(
109 "rust-analyzer failed to discover workspace, no Cargo.toml found, dirs searched: {}", 108 "rust-analyzer failed to discover workspace, no Cargo.toml found, dirs searched: {}",
110 ws_roots.iter().format_with(", ", |it, f| f(&it.display())) 109 ws_roots.iter().format_with(", ", |it, f| f(&it.display()))
@@ -124,7 +123,7 @@ pub fn main_loop(ws_roots: Vec<PathBuf>, config: Config, connection: Connection)
124 .map_err(|err| { 123 .map_err(|err| {
125 log::error!("failed to load workspace: {:#}", err); 124 log::error!("failed to load workspace: {:#}", err);
126 show_message( 125 show_message(
127 req::MessageType::Error, 126 lsp_types::MessageType::Error,
128 format!("rust-analyzer failed to load workspace: {:#}", err), 127 format!("rust-analyzer failed to load workspace: {:#}", err),
129 &connection.sender, 128 &connection.sender,
130 ); 129 );
@@ -142,23 +141,25 @@ pub fn main_loop(ws_roots: Vec<PathBuf>, config: Config, connection: Connection)
142 .collect::<std::result::Result<Vec<_>, _>>()?; 141 .collect::<std::result::Result<Vec<_>, _>>()?;
143 142
144 if let FilesWatcher::Client = config.files.watcher { 143 if let FilesWatcher::Client = config.files.watcher {
145 let registration_options = req::DidChangeWatchedFilesRegistrationOptions { 144 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
146 watchers: workspaces 145 watchers: workspaces
147 .iter() 146 .iter()
148 .flat_map(ProjectWorkspace::to_roots) 147 .flat_map(ProjectWorkspace::to_roots)
149 .filter(PackageRoot::is_member) 148 .filter(PackageRoot::is_member)
150 .map(|root| format!("{}/**/*.rs", root.path().display())) 149 .map(|root| format!("{}/**/*.rs", root.path().display()))
151 .map(|glob_pattern| req::FileSystemWatcher { glob_pattern, kind: None }) 150 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
152 .collect(), 151 .collect(),
153 }; 152 };
154 let registration = req::Registration { 153 let registration = lsp_types::Registration {
155 id: "file-watcher".to_string(), 154 id: "file-watcher".to_string(),
156 method: "workspace/didChangeWatchedFiles".to_string(), 155 method: "workspace/didChangeWatchedFiles".to_string(),
157 register_options: Some(serde_json::to_value(registration_options).unwrap()), 156 register_options: Some(serde_json::to_value(registration_options).unwrap()),
158 }; 157 };
159 let params = req::RegistrationParams { registrations: vec![registration] }; 158 let params = lsp_types::RegistrationParams { registrations: vec![registration] };
160 let request = 159 let request = request_new::<lsp_types::request::RegisterCapability>(
161 request_new::<req::RegisterCapability>(loop_state.next_request_id(), params); 160 loop_state.next_request_id(),
161 params,
162 );
162 connection.sender.send(request.into()).unwrap(); 163 connection.sender.send(request.into()).unwrap();
163 } 164 }
164 165
@@ -173,7 +174,6 @@ pub fn main_loop(ws_roots: Vec<PathBuf>, config: Config, connection: Connection)
173 }; 174 };
174 175
175 loop_state.roots_total = world_state.vfs.read().n_roots(); 176 loop_state.roots_total = world_state.vfs.read().n_roots();
176 loop_state.roots_scanned = 0;
177 177
178 let pool = ThreadPool::default(); 178 let pool = ThreadPool::default();
179 let (task_sender, task_receiver) = unbounded::<Task>(); 179 let (task_sender, task_receiver) = unbounded::<Task>();
@@ -258,14 +258,14 @@ impl fmt::Debug for Event {
258 258
259 match self { 259 match self {
260 Event::Msg(Message::Notification(not)) => { 260 Event::Msg(Message::Notification(not)) => {
261 if notification_is::<req::DidOpenTextDocument>(not) 261 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
262 || notification_is::<req::DidChangeTextDocument>(not) 262 || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
263 { 263 {
264 return debug_verbose_not(not, f); 264 return debug_verbose_not(not, f);
265 } 265 }
266 } 266 }
267 Event::Task(Task::Notify(not)) => { 267 Event::Task(Task::Notify(not)) => {
268 if notification_is::<req::PublishDiagnostics>(not) { 268 if notification_is::<lsp_types::notification::PublishDiagnostics>(not) {
269 return debug_verbose_not(not, f); 269 return debug_verbose_not(not, f);
270 } 270 }
271 } 271 }
@@ -400,10 +400,12 @@ fn loop_turn(
400 } 400 }
401 401
402 let max_in_flight_libs = pool.max_count().saturating_sub(2).max(1); 402 let max_in_flight_libs = pool.max_count().saturating_sub(2).max(1);
403 while loop_state.in_flight_libraries < max_in_flight_libs 403 while loop_state.in_flight_libraries < max_in_flight_libs {
404 && !loop_state.pending_libraries.is_empty() 404 let (root, files) = match loop_state.pending_libraries.pop() {
405 { 405 Some(it) => it,
406 let (root, files) = loop_state.pending_libraries.pop().unwrap(); 406 None => break,
407 };
408
407 loop_state.in_flight_libraries += 1; 409 loop_state.in_flight_libraries += 1;
408 let sender = libdata_sender.clone(); 410 let sender = libdata_sender.clone();
409 pool.execute(move || { 411 pool.execute(move || {
@@ -413,7 +415,8 @@ fn loop_turn(
413 }); 415 });
414 } 416 }
415 417
416 let show_progress = !loop_state.workspace_loaded; 418 let show_progress =
419 !loop_state.workspace_loaded && world_state.config.client_caps.work_done_progress;
417 420
418 if !loop_state.workspace_loaded 421 if !loop_state.workspace_loaded
419 && loop_state.roots_scanned == loop_state.roots_total 422 && loop_state.roots_scanned == loop_state.roots_total
@@ -450,7 +453,7 @@ fn loop_turn(
450 log::error!("overly long loop turn: {:?}", loop_duration); 453 log::error!("overly long loop turn: {:?}", loop_duration);
451 if env::var("RA_PROFILE").is_ok() { 454 if env::var("RA_PROFILE").is_ok() {
452 show_message( 455 show_message(
453 req::MessageType::Error, 456 lsp_types::MessageType::Error,
454 format!("overly long loop turn: {:?}", loop_duration), 457 format!("overly long loop turn: {:?}", loop_duration),
455 &connection.sender, 458 &connection.sender,
456 ); 459 );
@@ -500,45 +503,51 @@ fn on_request(
500 request_received, 503 request_received,
501 }; 504 };
502 pool_dispatcher 505 pool_dispatcher
503 .on_sync::<req::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))? 506 .on_sync::<lsp_ext::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))?
504 .on_sync::<req::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))? 507 .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
505 .on_sync::<req::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))? 508 .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
506 .on_sync::<req::SelectionRangeRequest>(|s, p| { 509 .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
507 handlers::handle_selection_range(s.snapshot(), p) 510 handlers::handle_selection_range(s.snapshot(), p)
508 })? 511 })?
509 .on_sync::<req::FindMatchingBrace>(|s, p| { 512 .on_sync::<lsp_ext::FindMatchingBrace>(|s, p| {
510 handlers::handle_find_matching_brace(s.snapshot(), p) 513 handlers::handle_find_matching_brace(s.snapshot(), p)
511 })? 514 })?
512 .on::<req::AnalyzerStatus>(handlers::handle_analyzer_status)? 515 .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)?
513 .on::<req::SyntaxTree>(handlers::handle_syntax_tree)? 516 .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)?
514 .on::<req::ExpandMacro>(handlers::handle_expand_macro)? 517 .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)?
515 .on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)? 518 .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)?
516 .on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)? 519 .on::<lsp_ext::Runnables>(handlers::handle_runnables)?
517 .on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)? 520 .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)?
518 .on::<req::GotoDefinition>(handlers::handle_goto_definition)? 521 .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)?
519 .on::<req::GotoImplementation>(handlers::handle_goto_implementation)? 522 .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)?
520 .on::<req::GotoTypeDefinition>(handlers::handle_goto_type_definition)? 523 .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
521 .on::<req::ParentModule>(handlers::handle_parent_module)? 524 .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)?
522 .on::<req::Runnables>(handlers::handle_runnables)? 525 .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)?
523 .on::<req::Completion>(handlers::handle_completion)? 526 .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
524 .on::<req::CodeActionRequest>(handlers::handle_code_action)? 527 .on::<lsp_types::request::Completion>(handlers::handle_completion)?
525 .on::<req::CodeLensRequest>(handlers::handle_code_lens)? 528 .on::<lsp_types::request::CodeActionRequest>(handlers::handle_code_action)?
526 .on::<req::CodeLensResolve>(handlers::handle_code_lens_resolve)? 529 .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)?
527 .on::<req::FoldingRangeRequest>(handlers::handle_folding_range)? 530 .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)?
528 .on::<req::SignatureHelpRequest>(handlers::handle_signature_help)? 531 .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)?
529 .on::<req::HoverRequest>(handlers::handle_hover)? 532 .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)?
530 .on::<req::PrepareRenameRequest>(handlers::handle_prepare_rename)? 533 .on::<lsp_types::request::HoverRequest>(handlers::handle_hover)?
531 .on::<req::Rename>(handlers::handle_rename)? 534 .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)?
532 .on::<req::References>(handlers::handle_references)? 535 .on::<lsp_types::request::Rename>(handlers::handle_rename)?
533 .on::<req::Formatting>(handlers::handle_formatting)? 536 .on::<lsp_types::request::References>(handlers::handle_references)?
534 .on::<req::DocumentHighlightRequest>(handlers::handle_document_highlight)? 537 .on::<lsp_types::request::Formatting>(handlers::handle_formatting)?
535 .on::<req::InlayHints>(handlers::handle_inlay_hints)? 538 .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)?
536 .on::<req::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)? 539 .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)?
537 .on::<req::CallHierarchyIncomingCalls>(handlers::handle_call_hierarchy_incoming)? 540 .on::<lsp_types::request::CallHierarchyIncomingCalls>(
538 .on::<req::CallHierarchyOutgoingCalls>(handlers::handle_call_hierarchy_outgoing)? 541 handlers::handle_call_hierarchy_incoming,
539 .on::<req::SemanticTokensRequest>(handlers::handle_semantic_tokens)? 542 )?
540 .on::<req::SemanticTokensRangeRequest>(handlers::handle_semantic_tokens_range)? 543 .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
541 .on::<req::Ssr>(handlers::handle_ssr)? 544 handlers::handle_call_hierarchy_outgoing,
545 )?
546 .on::<lsp_types::request::SemanticTokensRequest>(handlers::handle_semantic_tokens)?
547 .on::<lsp_types::request::SemanticTokensRangeRequest>(
548 handlers::handle_semantic_tokens_range,
549 )?
550 .on::<lsp_ext::Ssr>(handlers::handle_ssr)?
542 .finish(); 551 .finish();
543 Ok(()) 552 Ok(())
544} 553}
@@ -549,7 +558,7 @@ fn on_notification(
549 loop_state: &mut LoopState, 558 loop_state: &mut LoopState,
550 not: Notification, 559 not: Notification,
551) -> Result<()> { 560) -> Result<()> {
552 let not = match notification_cast::<req::Cancel>(not) { 561 let not = match notification_cast::<lsp_types::notification::Cancel>(not) {
553 Ok(params) => { 562 Ok(params) => {
554 let id: RequestId = match params.id { 563 let id: RequestId = match params.id {
555 NumberOrString::Number(id) => id.into(), 564 NumberOrString::Number(id) => id.into(),
@@ -567,7 +576,7 @@ fn on_notification(
567 } 576 }
568 Err(not) => not, 577 Err(not) => not,
569 }; 578 };
570 let not = match notification_cast::<req::DidOpenTextDocument>(not) { 579 let not = match notification_cast::<lsp_types::notification::DidOpenTextDocument>(not) {
571 Ok(params) => { 580 Ok(params) => {
572 let uri = params.text_document.uri; 581 let uri = params.text_document.uri;
573 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?; 582 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
@@ -580,11 +589,11 @@ fn on_notification(
580 } 589 }
581 Err(not) => not, 590 Err(not) => not,
582 }; 591 };
583 let not = match notification_cast::<req::DidChangeTextDocument>(not) { 592 let not = match notification_cast::<lsp_types::notification::DidChangeTextDocument>(not) {
584 Ok(params) => { 593 Ok(params) => {
585 let DidChangeTextDocumentParams { text_document, content_changes } = params; 594 let DidChangeTextDocumentParams { text_document, content_changes } = params;
586 let world = state.snapshot(); 595 let world = state.snapshot();
587 let file_id = text_document.try_conv_with(&world)?; 596 let file_id = from_proto::file_id(&world, &text_document.uri)?;
588 let line_index = world.analysis().file_line_index(file_id)?; 597 let line_index = world.analysis().file_line_index(file_id)?;
589 let uri = text_document.uri; 598 let uri = text_document.uri;
590 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?; 599 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
@@ -595,7 +604,7 @@ fn on_notification(
595 } 604 }
596 Err(not) => not, 605 Err(not) => not,
597 }; 606 };
598 let not = match notification_cast::<req::DidSaveTextDocument>(not) { 607 let not = match notification_cast::<lsp_types::notification::DidSaveTextDocument>(not) {
599 Ok(_params) => { 608 Ok(_params) => {
600 if let Some(flycheck) = &state.flycheck { 609 if let Some(flycheck) = &state.flycheck {
601 flycheck.update(); 610 flycheck.update();
@@ -604,7 +613,7 @@ fn on_notification(
604 } 613 }
605 Err(not) => not, 614 Err(not) => not,
606 }; 615 };
607 let not = match notification_cast::<req::DidCloseTextDocument>(not) { 616 let not = match notification_cast::<lsp_types::notification::DidCloseTextDocument>(not) {
608 Ok(params) => { 617 Ok(params) => {
609 let uri = params.text_document.uri; 618 let uri = params.text_document.uri;
610 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?; 619 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
@@ -612,22 +621,22 @@ fn on_notification(
612 loop_state.subscriptions.remove_sub(FileId(file_id.0)); 621 loop_state.subscriptions.remove_sub(FileId(file_id.0));
613 } 622 }
614 let params = 623 let params =
615 req::PublishDiagnosticsParams { uri, diagnostics: Vec::new(), version: None }; 624 lsp_types::PublishDiagnosticsParams { uri, diagnostics: Vec::new(), version: None };
616 let not = notification_new::<req::PublishDiagnostics>(params); 625 let not = notification_new::<lsp_types::notification::PublishDiagnostics>(params);
617 msg_sender.send(not.into()).unwrap(); 626 msg_sender.send(not.into()).unwrap();
618 return Ok(()); 627 return Ok(());
619 } 628 }
620 Err(not) => not, 629 Err(not) => not,
621 }; 630 };
622 let not = match notification_cast::<req::DidChangeConfiguration>(not) { 631 let not = match notification_cast::<lsp_types::notification::DidChangeConfiguration>(not) {
623 Ok(_) => { 632 Ok(_) => {
624 // As stated in https://github.com/microsoft/language-server-protocol/issues/676, 633 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
625 // this notification's parameters should be ignored and the actual config queried separately. 634 // this notification's parameters should be ignored and the actual config queried separately.
626 let request_id = loop_state.next_request_id(); 635 let request_id = loop_state.next_request_id();
627 let request = request_new::<req::WorkspaceConfiguration>( 636 let request = request_new::<lsp_types::request::WorkspaceConfiguration>(
628 request_id.clone(), 637 request_id.clone(),
629 req::ConfigurationParams { 638 lsp_types::ConfigurationParams {
630 items: vec![req::ConfigurationItem { 639 items: vec![lsp_types::ConfigurationItem {
631 scope_uri: None, 640 scope_uri: None,
632 section: Some("rust-analyzer".to_string()), 641 section: Some("rust-analyzer".to_string()),
633 }], 642 }],
@@ -640,7 +649,7 @@ fn on_notification(
640 } 649 }
641 Err(not) => not, 650 Err(not) => not,
642 }; 651 };
643 let not = match notification_cast::<req::DidChangeWatchedFiles>(not) { 652 let not = match notification_cast::<lsp_types::notification::DidChangeWatchedFiles>(not) {
644 Ok(params) => { 653 Ok(params) => {
645 let mut vfs = state.vfs.write(); 654 let mut vfs = state.vfs.write();
646 for change in params.changes { 655 for change in params.changes {
@@ -694,7 +703,7 @@ fn apply_document_changes(
694 line_index = Cow::Owned(LineIndex::new(&old_text)); 703 line_index = Cow::Owned(LineIndex::new(&old_text));
695 } 704 }
696 index_valid = IndexValid::UpToLineExclusive(range.start.line); 705 index_valid = IndexValid::UpToLineExclusive(range.start.line);
697 let range = range.conv_with(&line_index); 706 let range = from_proto::text_range(&line_index, range);
698 let mut text = old_text.to_owned(); 707 let mut text = old_text.to_owned();
699 match std::panic::catch_unwind(move || { 708 match std::panic::catch_unwind(move || {
700 text.replace_range(Range::<usize>::from(range), &change.text); 709 text.replace_range(Range::<usize>::from(range), &change.text);
@@ -742,12 +751,16 @@ fn on_check_task(
742 } 751 }
743 752
744 CheckTask::Status(progress) => { 753 CheckTask::Status(progress) => {
745 let params = req::ProgressParams { 754 if world_state.config.client_caps.work_done_progress {
746 token: req::ProgressToken::String("rustAnalyzer/cargoWatcher".to_string()), 755 let params = lsp_types::ProgressParams {
747 value: req::ProgressParamsValue::WorkDone(progress), 756 token: lsp_types::ProgressToken::String(
748 }; 757 "rustAnalyzer/cargoWatcher".to_string(),
749 let not = notification_new::<req::Progress>(params); 758 ),
750 task_sender.send(Task::Notify(not)).unwrap(); 759 value: lsp_types::ProgressParamsValue::WorkDone(progress),
760 };
761 let not = notification_new::<lsp_types::notification::Progress>(params);
762 task_sender.send(Task::Notify(not)).unwrap();
763 }
751 } 764 }
752 }; 765 };
753 766
@@ -768,8 +781,8 @@ fn on_diagnostic_task(task: DiagnosticTask, msg_sender: &Sender<Message>, state:
768 }; 781 };
769 782
770 let diagnostics = state.diagnostics.diagnostics_for(file_id).cloned().collect(); 783 let diagnostics = state.diagnostics.diagnostics_for(file_id).cloned().collect();
771 let params = req::PublishDiagnosticsParams { uri, diagnostics, version: None }; 784 let params = lsp_types::PublishDiagnosticsParams { uri, diagnostics, version: None };
772 let not = notification_new::<req::PublishDiagnostics>(params); 785 let not = notification_new::<lsp_types::notification::PublishDiagnostics>(params);
773 msg_sender.send(not.into()).unwrap(); 786 msg_sender.send(not.into()).unwrap();
774 } 787 }
775} 788}
@@ -782,10 +795,10 @@ fn send_startup_progress(sender: &Sender<Message>, loop_state: &mut LoopState) {
782 795
783 match (prev, loop_state.workspace_loaded) { 796 match (prev, loop_state.workspace_loaded) {
784 (None, false) => { 797 (None, false) => {
785 let work_done_progress_create = request_new::<req::WorkDoneProgressCreate>( 798 let work_done_progress_create = request_new::<lsp_types::request::WorkDoneProgressCreate>(
786 loop_state.next_request_id(), 799 loop_state.next_request_id(),
787 WorkDoneProgressCreateParams { 800 WorkDoneProgressCreateParams {
788 token: req::ProgressToken::String("rustAnalyzer/startup".into()), 801 token: lsp_types::ProgressToken::String("rustAnalyzer/startup".into()),
789 }, 802 },
790 ); 803 );
791 sender.send(work_done_progress_create.into()).unwrap(); 804 sender.send(work_done_progress_create.into()).unwrap();
@@ -817,10 +830,11 @@ fn send_startup_progress(sender: &Sender<Message>, loop_state: &mut LoopState) {
817 } 830 }
818 831
819 fn send_startup_progress_notif(sender: &Sender<Message>, work_done_progress: WorkDoneProgress) { 832 fn send_startup_progress_notif(sender: &Sender<Message>, work_done_progress: WorkDoneProgress) {
820 let notif = notification_new::<req::Progress>(req::ProgressParams { 833 let notif =
821 token: req::ProgressToken::String("rustAnalyzer/startup".into()), 834 notification_new::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
822 value: req::ProgressParamsValue::WorkDone(work_done_progress), 835 token: lsp_types::ProgressToken::String("rustAnalyzer/startup".into()),
823 }); 836 value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
837 });
824 sender.send(notif.into()).unwrap(); 838 sender.send(notif.into()).unwrap();
825 } 839 }
826} 840}
@@ -842,7 +856,7 @@ impl<'a> PoolDispatcher<'a> {
842 f: fn(&mut WorldState, R::Params) -> Result<R::Result>, 856 f: fn(&mut WorldState, R::Params) -> Result<R::Result>,
843 ) -> Result<&mut Self> 857 ) -> Result<&mut Self>
844 where 858 where
845 R: req::Request + 'static, 859 R: lsp_types::request::Request + 'static,
846 R::Params: DeserializeOwned + panic::UnwindSafe + 'static, 860 R::Params: DeserializeOwned + panic::UnwindSafe + 'static,
847 R::Result: Serialize + 'static, 861 R::Result: Serialize + 'static,
848 { 862 {
@@ -865,7 +879,7 @@ impl<'a> PoolDispatcher<'a> {
865 /// Dispatches the request onto thread pool 879 /// Dispatches the request onto thread pool
866 fn on<R>(&mut self, f: fn(WorldSnapshot, R::Params) -> Result<R::Result>) -> Result<&mut Self> 880 fn on<R>(&mut self, f: fn(WorldSnapshot, R::Params) -> Result<R::Result>) -> Result<&mut Self>
867 where 881 where
868 R: req::Request + 'static, 882 R: lsp_types::request::Request + 'static,
869 R::Params: DeserializeOwned + Send + 'static, 883 R::Params: DeserializeOwned + Send + 'static,
870 R::Result: Serialize + 'static, 884 R::Result: Serialize + 'static,
871 { 885 {
@@ -891,7 +905,7 @@ impl<'a> PoolDispatcher<'a> {
891 905
892 fn parse<R>(&mut self) -> Option<(RequestId, R::Params)> 906 fn parse<R>(&mut self) -> Option<(RequestId, R::Params)>
893 where 907 where
894 R: req::Request + 'static, 908 R: lsp_types::request::Request + 'static,
895 R::Params: DeserializeOwned + 'static, 909 R::Params: DeserializeOwned + 'static,
896 { 910 {
897 let req = self.req.take()?; 911 let req = self.req.take()?;
@@ -928,7 +942,7 @@ impl<'a> PoolDispatcher<'a> {
928 942
929fn result_to_task<R>(id: RequestId, result: Result<R::Result>) -> Task 943fn result_to_task<R>(id: RequestId, result: Result<R::Result>) -> Task
930where 944where
931 R: req::Request + 'static, 945 R: lsp_types::request::Request + 'static,
932 R::Params: DeserializeOwned + 'static, 946 R::Params: DeserializeOwned + 'static,
933 R::Result: Serialize + 'static, 947 R::Result: Serialize + 'static,
934{ 948{
@@ -984,10 +998,14 @@ fn update_file_notifications_on_threadpool(
984 } 998 }
985} 999}
986 1000
987pub fn show_message(typ: req::MessageType, message: impl Into<String>, sender: &Sender<Message>) { 1001pub fn show_message(
1002 typ: lsp_types::MessageType,
1003 message: impl Into<String>,
1004 sender: &Sender<Message>,
1005) {
988 let message = message.into(); 1006 let message = message.into();
989 let params = req::ShowMessageParams { typ, message }; 1007 let params = lsp_types::ShowMessageParams { typ, message };
990 let not = notification_new::<req::ShowMessage>(params); 1008 let not = notification_new::<lsp_types::notification::ShowMessage>(params);
991 sender.send(not.into()).unwrap(); 1009 sender.send(not.into()).unwrap();
992} 1010}
993 1011
diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs
index f4353af64..be8688bc3 100644
--- a/crates/rust-analyzer/src/main_loop/handlers.rs
+++ b/crates/rust-analyzer/src/main_loop/handlers.rs
@@ -22,6 +22,7 @@ use ra_ide::{
22 Assist, FileId, FilePosition, FileRange, Query, RangeInfo, Runnable, RunnableKind, SearchScope, 22 Assist, FileId, FilePosition, FileRange, Query, RangeInfo, Runnable, RunnableKind, SearchScope,
23}; 23};
24use ra_prof::profile; 24use ra_prof::profile;
25use ra_project_model::TargetKind;
25use ra_syntax::{AstNode, SyntaxKind, TextRange, TextSize}; 26use ra_syntax::{AstNode, SyntaxKind, TextRange, TextSize};
26use rustc_hash::FxHashMap; 27use rustc_hash::FxHashMap;
27use serde::{Deserialize, Serialize}; 28use serde::{Deserialize, Serialize};
@@ -31,18 +32,13 @@ use stdx::format_to;
31use crate::{ 32use crate::{
32 cargo_target_spec::CargoTargetSpec, 33 cargo_target_spec::CargoTargetSpec,
33 config::RustfmtConfig, 34 config::RustfmtConfig,
34 conv::{
35 to_call_hierarchy_item, to_location, Conv, ConvWith, FoldConvCtx, MapConvWith, TryConvWith,
36 TryConvWithToVec,
37 },
38 diagnostics::DiagnosticTask, 35 diagnostics::DiagnosticTask,
39 from_json, 36 from_json, from_proto,
40 req::{self, InlayHint, InlayHintsParams}, 37 lsp_ext::{self, InlayHint, InlayHintsParams},
41 semantic_tokens::SemanticTokensBuilder, 38 to_proto,
42 world::WorldSnapshot, 39 world::WorldSnapshot,
43 LspError, Result, 40 LspError, Result,
44}; 41};
45use ra_project_model::TargetKind;
46 42
47pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> { 43pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> {
48 let _p = profile("handle_analyzer_status"); 44 let _p = profile("handle_analyzer_status");
@@ -56,48 +52,51 @@ pub fn handle_analyzer_status(world: WorldSnapshot, _: ()) -> Result<String> {
56 Ok(buf) 52 Ok(buf)
57} 53}
58 54
59pub fn handle_syntax_tree(world: WorldSnapshot, params: req::SyntaxTreeParams) -> Result<String> { 55pub fn handle_syntax_tree(
56 world: WorldSnapshot,
57 params: lsp_ext::SyntaxTreeParams,
58) -> Result<String> {
60 let _p = profile("handle_syntax_tree"); 59 let _p = profile("handle_syntax_tree");
61 let id = params.text_document.try_conv_with(&world)?; 60 let id = from_proto::file_id(&world, &params.text_document.uri)?;
62 let line_index = world.analysis().file_line_index(id)?; 61 let line_index = world.analysis().file_line_index(id)?;
63 let text_range = params.range.map(|p| p.conv_with(&line_index)); 62 let text_range = params.range.map(|r| from_proto::text_range(&line_index, r));
64 let res = world.analysis().syntax_tree(id, text_range)?; 63 let res = world.analysis().syntax_tree(id, text_range)?;
65 Ok(res) 64 Ok(res)
66} 65}
67 66
68pub fn handle_expand_macro( 67pub fn handle_expand_macro(
69 world: WorldSnapshot, 68 world: WorldSnapshot,
70 params: req::ExpandMacroParams, 69 params: lsp_ext::ExpandMacroParams,
71) -> Result<Option<req::ExpandedMacro>> { 70) -> Result<Option<lsp_ext::ExpandedMacro>> {
72 let _p = profile("handle_expand_macro"); 71 let _p = profile("handle_expand_macro");
73 let file_id = params.text_document.try_conv_with(&world)?; 72 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
74 let line_index = world.analysis().file_line_index(file_id)?; 73 let line_index = world.analysis().file_line_index(file_id)?;
75 let offset = params.position.map(|p| p.conv_with(&line_index)); 74 let offset = params.position.map(|p| from_proto::offset(&line_index, p));
76 75
77 match offset { 76 match offset {
78 None => Ok(None), 77 None => Ok(None),
79 Some(offset) => { 78 Some(offset) => {
80 let res = world.analysis().expand_macro(FilePosition { file_id, offset })?; 79 let res = world.analysis().expand_macro(FilePosition { file_id, offset })?;
81 Ok(res.map(|it| req::ExpandedMacro { name: it.name, expansion: it.expansion })) 80 Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
82 } 81 }
83 } 82 }
84} 83}
85 84
86pub fn handle_selection_range( 85pub fn handle_selection_range(
87 world: WorldSnapshot, 86 world: WorldSnapshot,
88 params: req::SelectionRangeParams, 87 params: lsp_types::SelectionRangeParams,
89) -> Result<Option<Vec<req::SelectionRange>>> { 88) -> Result<Option<Vec<lsp_types::SelectionRange>>> {
90 let _p = profile("handle_selection_range"); 89 let _p = profile("handle_selection_range");
91 let file_id = params.text_document.try_conv_with(&world)?; 90 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
92 let line_index = world.analysis().file_line_index(file_id)?; 91 let line_index = world.analysis().file_line_index(file_id)?;
93 let res: Result<Vec<req::SelectionRange>> = params 92 let res: Result<Vec<lsp_types::SelectionRange>> = params
94 .positions 93 .positions
95 .into_iter() 94 .into_iter()
96 .map_conv_with(&line_index)
97 .map(|position| { 95 .map(|position| {
96 let offset = from_proto::offset(&line_index, position);
98 let mut ranges = Vec::new(); 97 let mut ranges = Vec::new();
99 { 98 {
100 let mut range = TextRange::new(position, position); 99 let mut range = TextRange::new(offset, offset);
101 loop { 100 loop {
102 ranges.push(range); 101 ranges.push(range);
103 let frange = FileRange { file_id, range }; 102 let frange = FileRange { file_id, range };
@@ -109,13 +108,13 @@ pub fn handle_selection_range(
109 } 108 }
110 } 109 }
111 } 110 }
112 let mut range = req::SelectionRange { 111 let mut range = lsp_types::SelectionRange {
113 range: ranges.last().unwrap().conv_with(&line_index), 112 range: to_proto::range(&line_index, *ranges.last().unwrap()),
114 parent: None, 113 parent: None,
115 }; 114 };
116 for r in ranges.iter().rev().skip(1) { 115 for &r in ranges.iter().rev().skip(1) {
117 range = req::SelectionRange { 116 range = lsp_types::SelectionRange {
118 range: r.conv_with(&line_index), 117 range: to_proto::range(&line_index, r),
119 parent: Some(Box::new(range)), 118 parent: Some(Box::new(range)),
120 } 119 }
121 } 120 }
@@ -128,57 +127,55 @@ pub fn handle_selection_range(
128 127
129pub fn handle_find_matching_brace( 128pub fn handle_find_matching_brace(
130 world: WorldSnapshot, 129 world: WorldSnapshot,
131 params: req::FindMatchingBraceParams, 130 params: lsp_ext::FindMatchingBraceParams,
132) -> Result<Vec<Position>> { 131) -> Result<Vec<Position>> {
133 let _p = profile("handle_find_matching_brace"); 132 let _p = profile("handle_find_matching_brace");
134 let file_id = params.text_document.try_conv_with(&world)?; 133 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
135 let line_index = world.analysis().file_line_index(file_id)?; 134 let line_index = world.analysis().file_line_index(file_id)?;
136 let res = params 135 let res = params
137 .offsets 136 .offsets
138 .into_iter() 137 .into_iter()
139 .map_conv_with(&line_index) 138 .map(|position| {
140 .map(|offset| { 139 let offset = from_proto::offset(&line_index, position);
141 if let Ok(Some(matching_brace_offset)) = 140 let offset = match world.analysis().matching_brace(FilePosition { file_id, offset }) {
142 world.analysis().matching_brace(FilePosition { file_id, offset }) 141 Ok(Some(matching_brace_offset)) => matching_brace_offset,
143 { 142 Err(_) | Ok(None) => offset,
144 matching_brace_offset 143 };
145 } else { 144 to_proto::position(&line_index, offset)
146 offset
147 }
148 }) 145 })
149 .map_conv_with(&line_index)
150 .collect(); 146 .collect();
151 Ok(res) 147 Ok(res)
152} 148}
153 149
154pub fn handle_join_lines( 150pub fn handle_join_lines(
155 world: WorldSnapshot, 151 world: WorldSnapshot,
156 params: req::JoinLinesParams, 152 params: lsp_ext::JoinLinesParams,
157) -> Result<req::SourceChange> { 153) -> Result<lsp_ext::SourceChange> {
158 let _p = profile("handle_join_lines"); 154 let _p = profile("handle_join_lines");
159 let frange = (&params.text_document, params.range).try_conv_with(&world)?; 155 let frange = from_proto::file_range(&world, params.text_document, params.range)?;
160 world.analysis().join_lines(frange)?.try_conv_with(&world) 156 let source_change = world.analysis().join_lines(frange)?;
157 to_proto::source_change(&world, source_change)
161} 158}
162 159
163pub fn handle_on_enter( 160pub fn handle_on_enter(
164 world: WorldSnapshot, 161 world: WorldSnapshot,
165 params: req::TextDocumentPositionParams, 162 params: lsp_types::TextDocumentPositionParams,
166) -> Result<Option<req::SourceChange>> { 163) -> Result<Option<lsp_ext::SourceChange>> {
167 let _p = profile("handle_on_enter"); 164 let _p = profile("handle_on_enter");
168 let position = params.try_conv_with(&world)?; 165 let position = from_proto::file_position(&world, params)?;
169 match world.analysis().on_enter(position)? { 166 match world.analysis().on_enter(position)? {
170 None => Ok(None), 167 None => Ok(None),
171 Some(edit) => Ok(Some(edit.try_conv_with(&world)?)), 168 Some(source_change) => to_proto::source_change(&world, source_change).map(Some),
172 } 169 }
173} 170}
174 171
175// Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`. 172// Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`.
176pub fn handle_on_type_formatting( 173pub fn handle_on_type_formatting(
177 world: WorldSnapshot, 174 world: WorldSnapshot,
178 params: req::DocumentOnTypeFormattingParams, 175 params: lsp_types::DocumentOnTypeFormattingParams,
179) -> Result<Option<Vec<TextEdit>>> { 176) -> Result<Option<Vec<TextEdit>>> {
180 let _p = profile("handle_on_type_formatting"); 177 let _p = profile("handle_on_type_formatting");
181 let mut position = params.text_document_position.try_conv_with(&world)?; 178 let mut position = from_proto::file_position(&world, params.text_document_position)?;
182 let line_index = world.analysis().file_line_index(position.file_id)?; 179 let line_index = world.analysis().file_line_index(position.file_id)?;
183 let line_endings = world.file_line_endings(position.file_id); 180 let line_endings = world.file_line_endings(position.file_id);
184 181
@@ -208,18 +205,17 @@ pub fn handle_on_type_formatting(
208 // This should be a single-file edit 205 // This should be a single-file edit
209 let edit = edit.source_file_edits.pop().unwrap(); 206 let edit = edit.source_file_edits.pop().unwrap();
210 207
211 let change: Vec<TextEdit> = edit.edit.conv_with((&line_index, line_endings)); 208 let change = to_proto::text_edit_vec(&line_index, line_endings, edit.edit);
212 Ok(Some(change)) 209 Ok(Some(change))
213} 210}
214 211
215pub fn handle_document_symbol( 212pub fn handle_document_symbol(
216 world: WorldSnapshot, 213 world: WorldSnapshot,
217 params: req::DocumentSymbolParams, 214 params: lsp_types::DocumentSymbolParams,
218) -> Result<Option<req::DocumentSymbolResponse>> { 215) -> Result<Option<lsp_types::DocumentSymbolResponse>> {
219 let _p = profile("handle_document_symbol"); 216 let _p = profile("handle_document_symbol");
220 let file_id = params.text_document.try_conv_with(&world)?; 217 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
221 let line_index = world.analysis().file_line_index(file_id)?; 218 let line_index = world.analysis().file_line_index(file_id)?;
222 let url = file_id.try_conv_with(&world)?;
223 219
224 let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new(); 220 let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
225 221
@@ -227,10 +223,10 @@ pub fn handle_document_symbol(
227 let doc_symbol = DocumentSymbol { 223 let doc_symbol = DocumentSymbol {
228 name: symbol.label, 224 name: symbol.label,
229 detail: symbol.detail, 225 detail: symbol.detail,
230 kind: symbol.kind.conv(), 226 kind: to_proto::symbol_kind(symbol.kind),
231 deprecated: Some(symbol.deprecated), 227 deprecated: Some(symbol.deprecated),
232 range: symbol.node_range.conv_with(&line_index), 228 range: to_proto::range(&line_index, symbol.node_range),
233 selection_range: symbol.navigation_range.conv_with(&line_index), 229 selection_range: to_proto::range(&line_index, symbol.navigation_range),
234 children: None, 230 children: None,
235 }; 231 };
236 parents.push((doc_symbol, symbol.parent)); 232 parents.push((doc_symbol, symbol.parent));
@@ -249,40 +245,41 @@ pub fn handle_document_symbol(
249 } 245 }
250 } 246 }
251 247
252 if world.config.client_caps.hierarchical_symbols { 248 let res = if world.config.client_caps.hierarchical_symbols {
253 Ok(Some(document_symbols.into())) 249 document_symbols.into()
254 } else { 250 } else {
251 let url = to_proto::url(&world, file_id)?;
255 let mut symbol_information = Vec::<SymbolInformation>::new(); 252 let mut symbol_information = Vec::<SymbolInformation>::new();
256 for symbol in document_symbols { 253 for symbol in document_symbols {
257 flatten_document_symbol(&symbol, None, &url, &mut symbol_information); 254 flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
258 } 255 }
256 symbol_information.into()
257 };
258 return Ok(Some(res));
259 259
260 Ok(Some(symbol_information.into())) 260 fn flatten_document_symbol(
261 } 261 symbol: &DocumentSymbol,
262} 262 container_name: Option<String>,
263 263 url: &Url,
264fn flatten_document_symbol( 264 res: &mut Vec<SymbolInformation>,
265 symbol: &DocumentSymbol, 265 ) {
266 container_name: Option<String>, 266 res.push(SymbolInformation {
267 url: &Url, 267 name: symbol.name.clone(),
268 res: &mut Vec<SymbolInformation>, 268 kind: symbol.kind,
269) { 269 deprecated: symbol.deprecated,
270 res.push(SymbolInformation { 270 location: Location::new(url.clone(), symbol.range),
271 name: symbol.name.clone(), 271 container_name: container_name,
272 kind: symbol.kind, 272 });
273 deprecated: symbol.deprecated,
274 location: Location::new(url.clone(), symbol.range),
275 container_name: container_name,
276 });
277 273
278 for child in symbol.children.iter().flatten() { 274 for child in symbol.children.iter().flatten() {
279 flatten_document_symbol(child, Some(symbol.name.clone()), url, res); 275 flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
276 }
280 } 277 }
281} 278}
282 279
283pub fn handle_workspace_symbol( 280pub fn handle_workspace_symbol(
284 world: WorldSnapshot, 281 world: WorldSnapshot,
285 params: req::WorkspaceSymbolParams, 282 params: lsp_types::WorkspaceSymbolParams,
286) -> Result<Option<Vec<SymbolInformation>>> { 283) -> Result<Option<Vec<SymbolInformation>>> {
287 let _p = profile("handle_workspace_symbol"); 284 let _p = profile("handle_workspace_symbol");
288 let all_symbols = params.query.contains('#'); 285 let all_symbols = params.query.contains('#');
@@ -313,8 +310,8 @@ pub fn handle_workspace_symbol(
313 for nav in world.analysis().symbol_search(query)? { 310 for nav in world.analysis().symbol_search(query)? {
314 let info = SymbolInformation { 311 let info = SymbolInformation {
315 name: nav.name().to_string(), 312 name: nav.name().to_string(),
316 kind: nav.kind().conv(), 313 kind: to_proto::symbol_kind(nav.kind()),
317 location: nav.try_conv_with(world)?, 314 location: to_proto::location(world, nav.file_range())?,
318 container_name: nav.container_name().map(|v| v.to_string()), 315 container_name: nav.container_name().map(|v| v.to_string()),
319 deprecated: None, 316 deprecated: None,
320 }; 317 };
@@ -326,63 +323,80 @@ pub fn handle_workspace_symbol(
326 323
327pub fn handle_goto_definition( 324pub fn handle_goto_definition(
328 world: WorldSnapshot, 325 world: WorldSnapshot,
329 params: req::GotoDefinitionParams, 326 params: lsp_types::GotoDefinitionParams,
330) -> Result<Option<req::GotoDefinitionResponse>> { 327) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
331 let _p = profile("handle_goto_definition"); 328 let _p = profile("handle_goto_definition");
332 let position = params.text_document_position_params.try_conv_with(&world)?; 329 let position = from_proto::file_position(&world, params.text_document_position_params)?;
333 let nav_info = match world.analysis().goto_definition(position)? { 330 let nav_info = match world.analysis().goto_definition(position)? {
334 None => return Ok(None), 331 None => return Ok(None),
335 Some(it) => it, 332 Some(it) => it,
336 }; 333 };
337 let res = (position.file_id, nav_info).try_conv_with(&world)?; 334 let res = to_proto::goto_definition_response(
335 &world,
336 FileRange { file_id: position.file_id, range: nav_info.range },
337 nav_info.info,
338 )?;
338 Ok(Some(res)) 339 Ok(Some(res))
339} 340}
340 341
341pub fn handle_goto_implementation( 342pub fn handle_goto_implementation(
342 world: WorldSnapshot, 343 world: WorldSnapshot,
343 params: req::GotoImplementationParams, 344 params: lsp_types::request::GotoImplementationParams,
344) -> Result<Option<req::GotoImplementationResponse>> { 345) -> Result<Option<lsp_types::request::GotoImplementationResponse>> {
345 let _p = profile("handle_goto_implementation"); 346 let _p = profile("handle_goto_implementation");
346 let position = params.text_document_position_params.try_conv_with(&world)?; 347 let position = from_proto::file_position(&world, params.text_document_position_params)?;
347 let nav_info = match world.analysis().goto_implementation(position)? { 348 let nav_info = match world.analysis().goto_implementation(position)? {
348 None => return Ok(None), 349 None => return Ok(None),
349 Some(it) => it, 350 Some(it) => it,
350 }; 351 };
351 let res = (position.file_id, nav_info).try_conv_with(&world)?; 352 let res = to_proto::goto_definition_response(
353 &world,
354 FileRange { file_id: position.file_id, range: nav_info.range },
355 nav_info.info,
356 )?;
352 Ok(Some(res)) 357 Ok(Some(res))
353} 358}
354 359
355pub fn handle_goto_type_definition( 360pub fn handle_goto_type_definition(
356 world: WorldSnapshot, 361 world: WorldSnapshot,
357 params: req::GotoTypeDefinitionParams, 362 params: lsp_types::request::GotoTypeDefinitionParams,
358) -> Result<Option<req::GotoTypeDefinitionResponse>> { 363) -> Result<Option<lsp_types::request::GotoTypeDefinitionResponse>> {
359 let _p = profile("handle_goto_type_definition"); 364 let _p = profile("handle_goto_type_definition");
360 let position = params.text_document_position_params.try_conv_with(&world)?; 365 let position = from_proto::file_position(&world, params.text_document_position_params)?;
361 let nav_info = match world.analysis().goto_type_definition(position)? { 366 let nav_info = match world.analysis().goto_type_definition(position)? {
362 None => return Ok(None), 367 None => return Ok(None),
363 Some(it) => it, 368 Some(it) => it,
364 }; 369 };
365 let res = (position.file_id, nav_info).try_conv_with(&world)?; 370 let res = to_proto::goto_definition_response(
371 &world,
372 FileRange { file_id: position.file_id, range: nav_info.range },
373 nav_info.info,
374 )?;
366 Ok(Some(res)) 375 Ok(Some(res))
367} 376}
368 377
369pub fn handle_parent_module( 378pub fn handle_parent_module(
370 world: WorldSnapshot, 379 world: WorldSnapshot,
371 params: req::TextDocumentPositionParams, 380 params: lsp_types::TextDocumentPositionParams,
372) -> Result<Vec<Location>> { 381) -> Result<Vec<Location>> {
373 let _p = profile("handle_parent_module"); 382 let _p = profile("handle_parent_module");
374 let position = params.try_conv_with(&world)?; 383 let position = from_proto::file_position(&world, params)?;
375 world.analysis().parent_module(position)?.iter().try_conv_with_to_vec(&world) 384 world
385 .analysis()
386 .parent_module(position)?
387 .into_iter()
388 .map(|it| to_proto::location(&world, it.file_range()))
389 .collect::<Result<Vec<_>>>()
376} 390}
377 391
378pub fn handle_runnables( 392pub fn handle_runnables(
379 world: WorldSnapshot, 393 world: WorldSnapshot,
380 params: req::RunnablesParams, 394 params: lsp_ext::RunnablesParams,
381) -> Result<Vec<req::Runnable>> { 395) -> Result<Vec<lsp_ext::Runnable>> {
382 let _p = profile("handle_runnables"); 396 let _p = profile("handle_runnables");
383 let file_id = params.text_document.try_conv_with(&world)?; 397 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
384 let line_index = world.analysis().file_line_index(file_id)?; 398 let line_index = world.analysis().file_line_index(file_id)?;
385 let offset = params.position.map(|it| it.conv_with(&line_index)); 399 let offset = params.position.map(|it| from_proto::offset(&line_index, it));
386 let mut res = Vec::new(); 400 let mut res = Vec::new();
387 let workspace_root = world.workspace_root_for(file_id); 401 let workspace_root = world.workspace_root_for(file_id);
388 let cargo_spec = CargoTargetSpec::for_file(&world, file_id)?; 402 let cargo_spec = CargoTargetSpec::for_file(&world, file_id)?;
@@ -408,7 +422,7 @@ pub fn handle_runnables(
408 match cargo_spec { 422 match cargo_spec {
409 Some(spec) => { 423 Some(spec) => {
410 for &cmd in ["check", "test"].iter() { 424 for &cmd in ["check", "test"].iter() {
411 res.push(req::Runnable { 425 res.push(lsp_ext::Runnable {
412 range: Default::default(), 426 range: Default::default(),
413 label: format!("cargo {} -p {}", cmd, spec.package), 427 label: format!("cargo {} -p {}", cmd, spec.package),
414 bin: "cargo".to_string(), 428 bin: "cargo".to_string(),
@@ -420,7 +434,7 @@ pub fn handle_runnables(
420 } 434 }
421 } 435 }
422 None => { 436 None => {
423 res.push(req::Runnable { 437 res.push(lsp_ext::Runnable {
424 range: Default::default(), 438 range: Default::default(),
425 label: "cargo check --workspace".to_string(), 439 label: "cargo check --workspace".to_string(),
426 bin: "cargo".to_string(), 440 bin: "cargo".to_string(),
@@ -436,10 +450,10 @@ pub fn handle_runnables(
436 450
437pub fn handle_completion( 451pub fn handle_completion(
438 world: WorldSnapshot, 452 world: WorldSnapshot,
439 params: req::CompletionParams, 453 params: lsp_types::CompletionParams,
440) -> Result<Option<req::CompletionResponse>> { 454) -> Result<Option<lsp_types::CompletionResponse>> {
441 let _p = profile("handle_completion"); 455 let _p = profile("handle_completion");
442 let position = params.text_document_position.try_conv_with(&world)?; 456 let position = from_proto::file_position(&world, params.text_document_position)?;
443 let completion_triggered_after_single_colon = { 457 let completion_triggered_after_single_colon = {
444 let mut res = false; 458 let mut res = false;
445 if let Some(ctx) = params.context { 459 if let Some(ctx) = params.context {
@@ -468,8 +482,10 @@ pub fn handle_completion(
468 }; 482 };
469 let line_index = world.analysis().file_line_index(position.file_id)?; 483 let line_index = world.analysis().file_line_index(position.file_id)?;
470 let line_endings = world.file_line_endings(position.file_id); 484 let line_endings = world.file_line_endings(position.file_id);
471 let items: Vec<CompletionItem> = 485 let items: Vec<CompletionItem> = items
472 items.into_iter().map(|item| item.conv_with((&line_index, line_endings))).collect(); 486 .into_iter()
487 .map(|item| to_proto::completion_item(&line_index, line_endings, item))
488 .collect();
473 489
474 Ok(Some(items.into())) 490 Ok(Some(items.into()))
475} 491}
@@ -479,52 +495,51 @@ pub fn handle_folding_range(
479 params: FoldingRangeParams, 495 params: FoldingRangeParams,
480) -> Result<Option<Vec<FoldingRange>>> { 496) -> Result<Option<Vec<FoldingRange>>> {
481 let _p = profile("handle_folding_range"); 497 let _p = profile("handle_folding_range");
482 let file_id = params.text_document.try_conv_with(&world)?; 498 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
483 let folds = world.analysis().folding_ranges(file_id)?; 499 let folds = world.analysis().folding_ranges(file_id)?;
484 let text = world.analysis().file_text(file_id)?; 500 let text = world.analysis().file_text(file_id)?;
485 let line_index = world.analysis().file_line_index(file_id)?; 501 let line_index = world.analysis().file_line_index(file_id)?;
486 let ctx = FoldConvCtx { 502 let line_folding_only = world.config.client_caps.line_folding_only;
487 text: &text, 503 let res = folds
488 line_index: &line_index, 504 .into_iter()
489 line_folding_only: world.config.client_caps.line_folding_only, 505 .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
490 }; 506 .collect();
491 let res = Some(folds.into_iter().map_conv_with(&ctx).collect()); 507 Ok(Some(res))
492 Ok(res)
493} 508}
494 509
495pub fn handle_signature_help( 510pub fn handle_signature_help(
496 world: WorldSnapshot, 511 world: WorldSnapshot,
497 params: req::SignatureHelpParams, 512 params: lsp_types::SignatureHelpParams,
498) -> Result<Option<req::SignatureHelp>> { 513) -> Result<Option<lsp_types::SignatureHelp>> {
499 let _p = profile("handle_signature_help"); 514 let _p = profile("handle_signature_help");
500 let position = params.text_document_position_params.try_conv_with(&world)?; 515 let position = from_proto::file_position(&world, params.text_document_position_params)?;
501 if let Some(call_info) = world.analysis().call_info(position)? { 516 let call_info = match world.analysis().call_info(position)? {
502 let concise = !world.config.call_info_full; 517 None => return Ok(None),
503 let mut active_parameter = call_info.active_parameter.map(|it| it as i64); 518 Some(it) => it,
504 if concise && call_info.signature.has_self_param { 519 };
505 active_parameter = active_parameter.map(|it| it.saturating_sub(1)); 520 let concise = !world.config.call_info_full;
506 } 521 let mut active_parameter = call_info.active_parameter.map(|it| it as i64);
507 let sig_info = call_info.signature.conv_with(concise); 522 if concise && call_info.signature.has_self_param {
508 523 active_parameter = active_parameter.map(|it| it.saturating_sub(1));
509 Ok(Some(req::SignatureHelp {
510 signatures: vec![sig_info],
511 active_signature: Some(0),
512 active_parameter,
513 }))
514 } else {
515 Ok(None)
516 } 524 }
525 let sig_info = to_proto::signature_information(call_info.signature, concise);
526
527 Ok(Some(lsp_types::SignatureHelp {
528 signatures: vec![sig_info],
529 active_signature: Some(0),
530 active_parameter,
531 }))
517} 532}
518 533
519pub fn handle_hover(world: WorldSnapshot, params: req::HoverParams) -> Result<Option<Hover>> { 534pub fn handle_hover(world: WorldSnapshot, params: lsp_types::HoverParams) -> Result<Option<Hover>> {
520 let _p = profile("handle_hover"); 535 let _p = profile("handle_hover");
521 let position = params.text_document_position_params.try_conv_with(&world)?; 536 let position = from_proto::file_position(&world, params.text_document_position_params)?;
522 let info = match world.analysis().hover(position)? { 537 let info = match world.analysis().hover(position)? {
523 None => return Ok(None), 538 None => return Ok(None),
524 Some(info) => info, 539 Some(info) => info,
525 }; 540 };
526 let line_index = world.analysis.file_line_index(position.file_id)?; 541 let line_index = world.analysis.file_line_index(position.file_id)?;
527 let range = info.range.conv_with(&line_index); 542 let range = to_proto::range(&line_index, info.range);
528 let res = Hover { 543 let res = Hover {
529 contents: HoverContents::Markup(MarkupContent { 544 contents: HoverContents::Markup(MarkupContent {
530 kind: MarkupKind::Markdown, 545 kind: MarkupKind::Markdown,
@@ -537,10 +552,10 @@ pub fn handle_hover(world: WorldSnapshot, params: req::HoverParams) -> Result<Op
537 552
538pub fn handle_prepare_rename( 553pub fn handle_prepare_rename(
539 world: WorldSnapshot, 554 world: WorldSnapshot,
540 params: req::TextDocumentPositionParams, 555 params: lsp_types::TextDocumentPositionParams,
541) -> Result<Option<PrepareRenameResponse>> { 556) -> Result<Option<PrepareRenameResponse>> {
542 let _p = profile("handle_prepare_rename"); 557 let _p = profile("handle_prepare_rename");
543 let position = params.try_conv_with(&world)?; 558 let position = from_proto::file_position(&world, params)?;
544 559
545 let optional_change = world.analysis().rename(position, "dummy")?; 560 let optional_change = world.analysis().rename(position, "dummy")?;
546 let range = match optional_change { 561 let range = match optional_change {
@@ -548,15 +563,14 @@ pub fn handle_prepare_rename(
548 Some(it) => it.range, 563 Some(it) => it.range,
549 }; 564 };
550 565
551 let file_id = params.text_document.try_conv_with(&world)?; 566 let line_index = world.analysis().file_line_index(position.file_id)?;
552 let line_index = world.analysis().file_line_index(file_id)?; 567 let range = to_proto::range(&line_index, range);
553 let range = range.conv_with(&line_index);
554 Ok(Some(PrepareRenameResponse::Range(range))) 568 Ok(Some(PrepareRenameResponse::Range(range)))
555} 569}
556 570
557pub fn handle_rename(world: WorldSnapshot, params: RenameParams) -> Result<Option<WorkspaceEdit>> { 571pub fn handle_rename(world: WorldSnapshot, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
558 let _p = profile("handle_rename"); 572 let _p = profile("handle_rename");
559 let position = params.text_document_position.try_conv_with(&world)?; 573 let position = from_proto::file_position(&world, params.text_document_position)?;
560 574
561 if params.new_name.is_empty() { 575 if params.new_name.is_empty() {
562 return Err(LspError::new( 576 return Err(LspError::new(
@@ -567,22 +581,21 @@ pub fn handle_rename(world: WorldSnapshot, params: RenameParams) -> Result<Optio
567 } 581 }
568 582
569 let optional_change = world.analysis().rename(position, &*params.new_name)?; 583 let optional_change = world.analysis().rename(position, &*params.new_name)?;
570 let change = match optional_change { 584 let source_change = match optional_change {
571 None => return Ok(None), 585 None => return Ok(None),
572 Some(it) => it.info, 586 Some(it) => it.info,
573 }; 587 };
574 588
575 let source_change_req = change.try_conv_with(&world)?; 589 let source_change = to_proto::source_change(&world, source_change)?;
576 590 Ok(Some(source_change.workspace_edit))
577 Ok(Some(source_change_req.workspace_edit))
578} 591}
579 592
580pub fn handle_references( 593pub fn handle_references(
581 world: WorldSnapshot, 594 world: WorldSnapshot,
582 params: req::ReferenceParams, 595 params: lsp_types::ReferenceParams,
583) -> Result<Option<Vec<Location>>> { 596) -> Result<Option<Vec<Location>>> {
584 let _p = profile("handle_references"); 597 let _p = profile("handle_references");
585 let position = params.text_document_position.try_conv_with(&world)?; 598 let position = from_proto::file_position(&world, params.text_document_position)?;
586 599
587 let refs = match world.analysis().find_all_refs(position, None)? { 600 let refs = match world.analysis().find_all_refs(position, None)? {
588 None => return Ok(None), 601 None => return Ok(None),
@@ -591,33 +604,13 @@ pub fn handle_references(
591 604
592 let locations = if params.context.include_declaration { 605 let locations = if params.context.include_declaration {
593 refs.into_iter() 606 refs.into_iter()
594 .filter_map(|reference| { 607 .filter_map(|reference| to_proto::location(&world, reference.file_range).ok())
595 let line_index =
596 world.analysis().file_line_index(reference.file_range.file_id).ok()?;
597 to_location(
598 reference.file_range.file_id,
599 reference.file_range.range,
600 &world,
601 &line_index,
602 )
603 .ok()
604 })
605 .collect() 608 .collect()
606 } else { 609 } else {
607 // Only iterate over the references if include_declaration was false 610 // Only iterate over the references if include_declaration was false
608 refs.references() 611 refs.references()
609 .iter() 612 .iter()
610 .filter_map(|reference| { 613 .filter_map(|reference| to_proto::location(&world, reference.file_range).ok())
611 let line_index =
612 world.analysis().file_line_index(reference.file_range.file_id).ok()?;
613 to_location(
614 reference.file_range.file_id,
615 reference.file_range.range,
616 &world,
617 &line_index,
618 )
619 .ok()
620 })
621 .collect() 614 .collect()
622 }; 615 };
623 616
@@ -629,12 +622,12 @@ pub fn handle_formatting(
629 params: DocumentFormattingParams, 622 params: DocumentFormattingParams,
630) -> Result<Option<Vec<TextEdit>>> { 623) -> Result<Option<Vec<TextEdit>>> {
631 let _p = profile("handle_formatting"); 624 let _p = profile("handle_formatting");
632 let file_id = params.text_document.try_conv_with(&world)?; 625 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
633 let file = world.analysis().file_text(file_id)?; 626 let file = world.analysis().file_text(file_id)?;
634 let crate_ids = world.analysis().crate_for(file_id)?; 627 let crate_ids = world.analysis().crate_for(file_id)?;
635 628
636 let file_line_index = world.analysis().file_line_index(file_id)?; 629 let file_line_index = world.analysis().file_line_index(file_id)?;
637 let end_position = TextSize::of(file.as_str()).conv_with(&file_line_index); 630 let end_position = to_proto::position(&file_line_index, TextSize::of(file.as_str()));
638 631
639 let mut rustfmt = match &world.config.rustfmt { 632 let mut rustfmt = match &world.config.rustfmt {
640 RustfmtConfig::Rustfmt { extra_args } => { 633 RustfmtConfig::Rustfmt { extra_args } => {
@@ -700,33 +693,14 @@ pub fn handle_formatting(
700 }])) 693 }]))
701} 694}
702 695
703fn create_single_code_action(assist: Assist, world: &WorldSnapshot) -> Result<CodeAction> {
704 let arg = to_value(assist.source_change.try_conv_with(world)?)?;
705 let title = assist.label;
706 let command = Command {
707 title: title.clone(),
708 command: "rust-analyzer.applySourceChange".to_string(),
709 arguments: Some(vec![arg]),
710 };
711
712 Ok(CodeAction {
713 title,
714 kind: Some(String::new()),
715 diagnostics: None,
716 edit: None,
717 command: Some(command),
718 is_preferred: None,
719 })
720}
721
722pub fn handle_code_action( 696pub fn handle_code_action(
723 world: WorldSnapshot, 697 world: WorldSnapshot,
724 params: req::CodeActionParams, 698 params: lsp_types::CodeActionParams,
725) -> Result<Option<CodeActionResponse>> { 699) -> Result<Option<CodeActionResponse>> {
726 let _p = profile("handle_code_action"); 700 let _p = profile("handle_code_action");
727 let file_id = params.text_document.try_conv_with(&world)?; 701 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
728 let line_index = world.analysis().file_line_index(file_id)?; 702 let line_index = world.analysis().file_line_index(file_id)?;
729 let range = params.range.conv_with(&line_index); 703 let range = from_proto::text_range(&line_index, params.range);
730 704
731 let diagnostics = world.analysis().diagnostics(file_id)?; 705 let diagnostics = world.analysis().diagnostics(file_id)?;
732 let mut res = CodeActionResponse::default(); 706 let mut res = CodeActionResponse::default();
@@ -739,7 +713,7 @@ pub fn handle_code_action(
739 713
740 for source_edit in fixes_from_diagnostics { 714 for source_edit in fixes_from_diagnostics {
741 let title = source_edit.label.clone(); 715 let title = source_edit.label.clone();
742 let edit = source_edit.try_conv_with(&world)?; 716 let edit = to_proto::source_change(&world, source_edit)?;
743 717
744 let command = Command { 718 let command = Command {
745 title, 719 title,
@@ -758,7 +732,7 @@ pub fn handle_code_action(
758 } 732 }
759 733
760 for fix in world.check_fixes.get(&file_id).into_iter().flatten() { 734 for fix in world.check_fixes.get(&file_id).into_iter().flatten() {
761 let fix_range = fix.range.conv_with(&line_index); 735 let fix_range = from_proto::text_range(&line_index, fix.range);
762 if fix_range.intersect(range).is_none() { 736 if fix_range.intersect(range).is_none() {
763 continue; 737 continue;
764 } 738 }
@@ -779,21 +753,21 @@ pub fn handle_code_action(
779 .1 753 .1
780 .push(assist), 754 .push(assist),
781 None => { 755 None => {
782 res.push(create_single_code_action(assist, &world)?.into()); 756 res.push(to_proto::code_action(&world, assist)?.into());
783 } 757 }
784 } 758 }
785 } 759 }
786 760
787 for (group_label, (idx, assists)) in grouped_assists { 761 for (group_label, (idx, assists)) in grouped_assists {
788 if assists.len() == 1 { 762 if assists.len() == 1 {
789 res[idx] = 763 res[idx] = to_proto::code_action(&world, assists.into_iter().next().unwrap())?.into();
790 create_single_code_action(assists.into_iter().next().unwrap(), &world)?.into();
791 } else { 764 } else {
792 let title = group_label; 765 let title = group_label;
793 766
794 let mut arguments = Vec::with_capacity(assists.len()); 767 let mut arguments = Vec::with_capacity(assists.len());
795 for assist in assists { 768 for assist in assists {
796 arguments.push(to_value(assist.source_change.try_conv_with(&world)?)?); 769 let source_change = to_proto::source_change(&world, assist.source_change)?;
770 arguments.push(to_value(source_change)?);
797 } 771 }
798 772
799 let command = Some(Command { 773 let command = Some(Command {
@@ -835,10 +809,10 @@ pub fn handle_code_action(
835 809
836pub fn handle_code_lens( 810pub fn handle_code_lens(
837 world: WorldSnapshot, 811 world: WorldSnapshot,
838 params: req::CodeLensParams, 812 params: lsp_types::CodeLensParams,
839) -> Result<Option<Vec<CodeLens>>> { 813) -> Result<Option<Vec<CodeLens>>> {
840 let _p = profile("handle_code_lens"); 814 let _p = profile("handle_code_lens");
841 let file_id = params.text_document.try_conv_with(&world)?; 815 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
842 let line_index = world.analysis().file_line_index(file_id)?; 816 let line_index = world.analysis().file_line_index(file_id)?;
843 817
844 let mut lenses: Vec<CodeLens> = Default::default(); 818 let mut lenses: Vec<CodeLens> = Default::default();
@@ -902,10 +876,10 @@ pub fn handle_code_lens(
902 _ => false, 876 _ => false,
903 }) 877 })
904 .map(|it| { 878 .map(|it| {
905 let range = it.node_range.conv_with(&line_index); 879 let range = to_proto::range(&line_index, it.node_range);
906 let pos = range.start; 880 let pos = range.start;
907 let lens_params = req::GotoImplementationParams { 881 let lens_params = lsp_types::request::GotoImplementationParams {
908 text_document_position_params: req::TextDocumentPositionParams::new( 882 text_document_position_params: lsp_types::TextDocumentPositionParams::new(
909 params.text_document.clone(), 883 params.text_document.clone(),
910 pos, 884 pos,
911 ), 885 ),
@@ -926,7 +900,7 @@ pub fn handle_code_lens(
926#[derive(Debug, Serialize, Deserialize)] 900#[derive(Debug, Serialize, Deserialize)]
927#[serde(rename_all = "camelCase")] 901#[serde(rename_all = "camelCase")]
928enum CodeLensResolveData { 902enum CodeLensResolveData {
929 Impls(req::GotoImplementationParams), 903 Impls(lsp_types::request::GotoImplementationParams),
930} 904}
931 905
932pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Result<CodeLens> { 906pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Result<CodeLens> {
@@ -937,9 +911,9 @@ pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Re
937 Some(CodeLensResolveData::Impls(lens_params)) => { 911 Some(CodeLensResolveData::Impls(lens_params)) => {
938 let locations: Vec<Location> = 912 let locations: Vec<Location> =
939 match handle_goto_implementation(world, lens_params.clone())? { 913 match handle_goto_implementation(world, lens_params.clone())? {
940 Some(req::GotoDefinitionResponse::Scalar(loc)) => vec![loc], 914 Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
941 Some(req::GotoDefinitionResponse::Array(locs)) => locs, 915 Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs,
942 Some(req::GotoDefinitionResponse::Link(links)) => links 916 Some(lsp_types::GotoDefinitionResponse::Link(links)) => links
943 .into_iter() 917 .into_iter()
944 .map(|link| Location::new(link.target_uri, link.target_selection_range)) 918 .map(|link| Location::new(link.target_uri, link.target_selection_range))
945 .collect(), 919 .collect(),
@@ -976,37 +950,39 @@ pub fn handle_code_lens_resolve(world: WorldSnapshot, code_lens: CodeLens) -> Re
976 950
977pub fn handle_document_highlight( 951pub fn handle_document_highlight(
978 world: WorldSnapshot, 952 world: WorldSnapshot,
979 params: req::DocumentHighlightParams, 953 params: lsp_types::DocumentHighlightParams,
980) -> Result<Option<Vec<DocumentHighlight>>> { 954) -> Result<Option<Vec<DocumentHighlight>>> {
981 let _p = profile("handle_document_highlight"); 955 let _p = profile("handle_document_highlight");
982 let file_id = params.text_document_position_params.text_document.try_conv_with(&world)?; 956 let position = from_proto::file_position(&world, params.text_document_position_params)?;
983 let line_index = world.analysis().file_line_index(file_id)?; 957 let line_index = world.analysis().file_line_index(position.file_id)?;
984 958
985 let refs = match world.analysis().find_all_refs( 959 let refs = match world
986 params.text_document_position_params.try_conv_with(&world)?, 960 .analysis()
987 Some(SearchScope::single_file(file_id)), 961 .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
988 )? { 962 {
989 None => return Ok(None), 963 None => return Ok(None),
990 Some(refs) => refs, 964 Some(refs) => refs,
991 }; 965 };
992 966
993 Ok(Some( 967 let res = refs
994 refs.into_iter() 968 .into_iter()
995 .filter(|reference| reference.file_range.file_id == file_id) 969 .filter(|reference| reference.file_range.file_id == position.file_id)
996 .map(|reference| DocumentHighlight { 970 .map(|reference| DocumentHighlight {
997 range: reference.file_range.range.conv_with(&line_index), 971 range: to_proto::range(&line_index, reference.file_range.range),
998 kind: reference.access.map(|it| it.conv()), 972 kind: reference.access.map(to_proto::document_highlight_kind),
999 }) 973 })
1000 .collect(), 974 .collect();
1001 )) 975 Ok(Some(res))
1002} 976}
1003 977
1004pub fn handle_ssr(world: WorldSnapshot, params: req::SsrParams) -> Result<req::SourceChange> { 978pub fn handle_ssr(
979 world: WorldSnapshot,
980 params: lsp_ext::SsrParams,
981) -> Result<lsp_ext::SourceChange> {
1005 let _p = profile("handle_ssr"); 982 let _p = profile("handle_ssr");
1006 world 983 let source_change =
1007 .analysis() 984 world.analysis().structural_search_replace(&params.query, params.parse_only)??;
1008 .structural_search_replace(&params.query, params.parse_only)?? 985 to_proto::source_change(&world, source_change)
1009 .try_conv_with(&world)
1010} 986}
1011 987
1012pub fn publish_diagnostics(world: &WorldSnapshot, file_id: FileId) -> Result<DiagnosticTask> { 988pub fn publish_diagnostics(world: &WorldSnapshot, file_id: FileId) -> Result<DiagnosticTask> {
@@ -1017,8 +993,8 @@ pub fn publish_diagnostics(world: &WorldSnapshot, file_id: FileId) -> Result<Dia
1017 .diagnostics(file_id)? 993 .diagnostics(file_id)?
1018 .into_iter() 994 .into_iter()
1019 .map(|d| Diagnostic { 995 .map(|d| Diagnostic {
1020 range: d.range.conv_with(&line_index), 996 range: to_proto::range(&line_index, d.range),
1021 severity: Some(d.severity.conv()), 997 severity: Some(to_proto::diagnostic_severity(d.severity)),
1022 code: None, 998 code: None,
1023 source: Some("rust-analyzer".to_string()), 999 source: Some("rust-analyzer".to_string()),
1024 message: d.message, 1000 message: d.message,
@@ -1033,7 +1009,7 @@ fn to_lsp_runnable(
1033 world: &WorldSnapshot, 1009 world: &WorldSnapshot,
1034 file_id: FileId, 1010 file_id: FileId,
1035 runnable: Runnable, 1011 runnable: Runnable,
1036) -> Result<req::Runnable> { 1012) -> Result<lsp_ext::Runnable> {
1037 let spec = CargoTargetSpec::for_file(world, file_id)?; 1013 let spec = CargoTargetSpec::for_file(world, file_id)?;
1038 let (args, extra_args) = CargoTargetSpec::runnable_args(spec, &runnable.kind)?; 1014 let (args, extra_args) = CargoTargetSpec::runnable_args(spec, &runnable.kind)?;
1039 let line_index = world.analysis().file_line_index(file_id)?; 1015 let line_index = world.analysis().file_line_index(file_id)?;
@@ -1044,8 +1020,8 @@ fn to_lsp_runnable(
1044 RunnableKind::DocTest { test_id, .. } => format!("doctest {}", test_id), 1020 RunnableKind::DocTest { test_id, .. } => format!("doctest {}", test_id),
1045 RunnableKind::Bin => "run binary".to_string(), 1021 RunnableKind::Bin => "run binary".to_string(),
1046 }; 1022 };
1047 Ok(req::Runnable { 1023 Ok(lsp_ext::Runnable {
1048 range: runnable.range.conv_with(&line_index), 1024 range: to_proto::range(&line_index, runnable.range),
1049 label, 1025 label,
1050 bin: "cargo".to_string(), 1026 bin: "cargo".to_string(),
1051 args, 1027 args,
@@ -1064,13 +1040,13 @@ pub fn handle_inlay_hints(
1064 params: InlayHintsParams, 1040 params: InlayHintsParams,
1065) -> Result<Vec<InlayHint>> { 1041) -> Result<Vec<InlayHint>> {
1066 let _p = profile("handle_inlay_hints"); 1042 let _p = profile("handle_inlay_hints");
1067 let file_id = params.text_document.try_conv_with(&world)?; 1043 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
1068 let analysis = world.analysis(); 1044 let analysis = world.analysis();
1069 let line_index = analysis.file_line_index(file_id)?; 1045 let line_index = analysis.file_line_index(file_id)?;
1070 Ok(analysis 1046 Ok(analysis
1071 .inlay_hints(file_id, &world.config.inlay_hints)? 1047 .inlay_hints(file_id, &world.config.inlay_hints)?
1072 .into_iter() 1048 .into_iter()
1073 .map_conv_with(&line_index) 1049 .map(|it| to_proto::inlay_int(&line_index, it))
1074 .collect()) 1050 .collect())
1075} 1051}
1076 1052
@@ -1079,21 +1055,19 @@ pub fn handle_call_hierarchy_prepare(
1079 params: CallHierarchyPrepareParams, 1055 params: CallHierarchyPrepareParams,
1080) -> Result<Option<Vec<CallHierarchyItem>>> { 1056) -> Result<Option<Vec<CallHierarchyItem>>> {
1081 let _p = profile("handle_call_hierarchy_prepare"); 1057 let _p = profile("handle_call_hierarchy_prepare");
1082 let position = params.text_document_position_params.try_conv_with(&world)?; 1058 let position = from_proto::file_position(&world, params.text_document_position_params)?;
1083 let file_id = position.file_id;
1084 1059
1085 let nav_info = match world.analysis().call_hierarchy(position)? { 1060 let nav_info = match world.analysis().call_hierarchy(position)? {
1086 None => return Ok(None), 1061 None => return Ok(None),
1087 Some(it) => it, 1062 Some(it) => it,
1088 }; 1063 };
1089 1064
1090 let line_index = world.analysis().file_line_index(file_id)?; 1065 let RangeInfo { range: _, info: navs } = nav_info;
1091 let RangeInfo { range, info: navs } = nav_info;
1092 let res = navs 1066 let res = navs
1093 .into_iter() 1067 .into_iter()
1094 .filter(|it| it.kind() == SyntaxKind::FN_DEF) 1068 .filter(|it| it.kind() == SyntaxKind::FN_DEF)
1095 .filter_map(|it| to_call_hierarchy_item(file_id, range, &world, &line_index, it).ok()) 1069 .map(|it| to_proto::call_hierarchy_item(&world, it))
1096 .collect(); 1070 .collect::<Result<Vec<_>>>()?;
1097 1071
1098 Ok(Some(res)) 1072 Ok(Some(res))
1099} 1073}
@@ -1106,7 +1080,7 @@ pub fn handle_call_hierarchy_incoming(
1106 let item = params.item; 1080 let item = params.item;
1107 1081
1108 let doc = TextDocumentIdentifier::new(item.uri); 1082 let doc = TextDocumentIdentifier::new(item.uri);
1109 let frange: FileRange = (&doc, item.range).try_conv_with(&world)?; 1083 let frange = from_proto::file_range(&world, doc, item.range)?;
1110 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() }; 1084 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1111 1085
1112 let call_items = match world.analysis().incoming_calls(fpos)? { 1086 let call_items = match world.analysis().incoming_calls(fpos)? {
@@ -1119,11 +1093,14 @@ pub fn handle_call_hierarchy_incoming(
1119 for call_item in call_items.into_iter() { 1093 for call_item in call_items.into_iter() {
1120 let file_id = call_item.target.file_id(); 1094 let file_id = call_item.target.file_id();
1121 let line_index = world.analysis().file_line_index(file_id)?; 1095 let line_index = world.analysis().file_line_index(file_id)?;
1122 let range = call_item.target.range(); 1096 let item = to_proto::call_hierarchy_item(&world, call_item.target)?;
1123 let item = to_call_hierarchy_item(file_id, range, &world, &line_index, call_item.target)?;
1124 res.push(CallHierarchyIncomingCall { 1097 res.push(CallHierarchyIncomingCall {
1125 from: item, 1098 from: item,
1126 from_ranges: call_item.ranges.iter().map(|it| it.conv_with(&line_index)).collect(), 1099 from_ranges: call_item
1100 .ranges
1101 .into_iter()
1102 .map(|it| to_proto::range(&line_index, it))
1103 .collect(),
1127 }); 1104 });
1128 } 1105 }
1129 1106
@@ -1138,7 +1115,7 @@ pub fn handle_call_hierarchy_outgoing(
1138 let item = params.item; 1115 let item = params.item;
1139 1116
1140 let doc = TextDocumentIdentifier::new(item.uri); 1117 let doc = TextDocumentIdentifier::new(item.uri);
1141 let frange: FileRange = (&doc, item.range).try_conv_with(&world)?; 1118 let frange = from_proto::file_range(&world, doc, item.range)?;
1142 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() }; 1119 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1143 1120
1144 let call_items = match world.analysis().outgoing_calls(fpos)? { 1121 let call_items = match world.analysis().outgoing_calls(fpos)? {
@@ -1151,11 +1128,14 @@ pub fn handle_call_hierarchy_outgoing(
1151 for call_item in call_items.into_iter() { 1128 for call_item in call_items.into_iter() {
1152 let file_id = call_item.target.file_id(); 1129 let file_id = call_item.target.file_id();
1153 let line_index = world.analysis().file_line_index(file_id)?; 1130 let line_index = world.analysis().file_line_index(file_id)?;
1154 let range = call_item.target.range(); 1131 let item = to_proto::call_hierarchy_item(&world, call_item.target)?;
1155 let item = to_call_hierarchy_item(file_id, range, &world, &line_index, call_item.target)?;
1156 res.push(CallHierarchyOutgoingCall { 1132 res.push(CallHierarchyOutgoingCall {
1157 to: item, 1133 to: item,
1158 from_ranges: call_item.ranges.iter().map(|it| it.conv_with(&line_index)).collect(), 1134 from_ranges: call_item
1135 .ranges
1136 .into_iter()
1137 .map(|it| to_proto::range(&line_index, it))
1138 .collect(),
1159 }); 1139 });
1160 } 1140 }
1161 1141
@@ -1168,26 +1148,13 @@ pub fn handle_semantic_tokens(
1168) -> Result<Option<SemanticTokensResult>> { 1148) -> Result<Option<SemanticTokensResult>> {
1169 let _p = profile("handle_semantic_tokens"); 1149 let _p = profile("handle_semantic_tokens");
1170 1150
1171 let file_id = params.text_document.try_conv_with(&world)?; 1151 let file_id = from_proto::file_id(&world, &params.text_document.uri)?;
1172 let text = world.analysis().file_text(file_id)?; 1152 let text = world.analysis().file_text(file_id)?;
1173 let line_index = world.analysis().file_line_index(file_id)?; 1153 let line_index = world.analysis().file_line_index(file_id)?;
1174 1154
1175 let mut builder = SemanticTokensBuilder::default(); 1155 let highlights = world.analysis().highlight(file_id)?;
1176 1156 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1177 for highlight_range in world.analysis().highlight(file_id)?.into_iter() { 1157 Ok(Some(semantic_tokens.into()))
1178 let (token_index, modifier_bitset) = highlight_range.highlight.conv();
1179 for mut range in line_index.lines(highlight_range.range) {
1180 if text[range].ends_with('\n') {
1181 range = TextRange::new(range.start(), range.end() - TextSize::of('\n'));
1182 }
1183 let range = range.conv_with(&line_index);
1184 builder.push(range, token_index, modifier_bitset);
1185 }
1186 }
1187
1188 let tokens = builder.build();
1189
1190 Ok(Some(tokens.into()))
1191} 1158}
1192 1159
1193pub fn handle_semantic_tokens_range( 1160pub fn handle_semantic_tokens_range(
@@ -1196,17 +1163,11 @@ pub fn handle_semantic_tokens_range(
1196) -> Result<Option<SemanticTokensRangeResult>> { 1163) -> Result<Option<SemanticTokensRangeResult>> {
1197 let _p = profile("handle_semantic_tokens_range"); 1164 let _p = profile("handle_semantic_tokens_range");
1198 1165
1199 let frange = (&params.text_document, params.range).try_conv_with(&world)?; 1166 let frange = from_proto::file_range(&world, params.text_document, params.range)?;
1167 let text = world.analysis().file_text(frange.file_id)?;
1200 let line_index = world.analysis().file_line_index(frange.file_id)?; 1168 let line_index = world.analysis().file_line_index(frange.file_id)?;
1201 1169
1202 let mut builder = SemanticTokensBuilder::default(); 1170 let highlights = world.analysis().highlight_range(frange)?;
1203 1171 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1204 for highlight_range in world.analysis().highlight_range(frange)?.into_iter() { 1172 Ok(Some(semantic_tokens.into()))
1205 let (token_type, token_modifiers) = highlight_range.highlight.conv();
1206 builder.push(highlight_range.range.conv_with(&line_index), token_type, token_modifiers);
1207 }
1208
1209 let tokens = builder.build();
1210
1211 Ok(Some(tokens.into()))
1212} 1173}
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs
new file mode 100644
index 000000000..33c2fd595
--- /dev/null
+++ b/crates/rust-analyzer/src/to_proto.rs
@@ -0,0 +1,592 @@
1//! Conversion of rust-analyzer specific types to lsp_types equivalents.
2use ra_db::{FileId, FileRange};
3use ra_ide::{
4 translate_offset_with_edit, Assist, CompletionItem, CompletionItemKind, Documentation,
5 FileSystemEdit, Fold, FoldKind, FunctionSignature, Highlight, HighlightModifier, HighlightTag,
6 HighlightedRange, InlayHint, InlayKind, InsertTextFormat, LineIndex, NavigationTarget,
7 ReferenceAccess, Severity, SourceChange, SourceFileEdit,
8};
9use ra_syntax::{SyntaxKind, TextRange, TextSize};
10use ra_text_edit::{Indel, TextEdit};
11use ra_vfs::LineEndings;
12
13use crate::{lsp_ext, semantic_tokens, world::WorldSnapshot, Result};
14
15pub(crate) fn position(line_index: &LineIndex, offset: TextSize) -> lsp_types::Position {
16 let line_col = line_index.line_col(offset);
17 let line = u64::from(line_col.line);
18 let character = u64::from(line_col.col_utf16);
19 lsp_types::Position::new(line, character)
20}
21
22pub(crate) fn range(line_index: &LineIndex, range: TextRange) -> lsp_types::Range {
23 let start = position(line_index, range.start());
24 let end = position(line_index, range.end());
25 lsp_types::Range::new(start, end)
26}
27
28pub(crate) fn symbol_kind(syntax_kind: SyntaxKind) -> lsp_types::SymbolKind {
29 match syntax_kind {
30 SyntaxKind::FN_DEF => lsp_types::SymbolKind::Function,
31 SyntaxKind::STRUCT_DEF => lsp_types::SymbolKind::Struct,
32 SyntaxKind::ENUM_DEF => lsp_types::SymbolKind::Enum,
33 SyntaxKind::ENUM_VARIANT => lsp_types::SymbolKind::EnumMember,
34 SyntaxKind::TRAIT_DEF => lsp_types::SymbolKind::Interface,
35 SyntaxKind::MACRO_CALL => lsp_types::SymbolKind::Function,
36 SyntaxKind::MODULE => lsp_types::SymbolKind::Module,
37 SyntaxKind::TYPE_ALIAS_DEF => lsp_types::SymbolKind::TypeParameter,
38 SyntaxKind::RECORD_FIELD_DEF => lsp_types::SymbolKind::Field,
39 SyntaxKind::STATIC_DEF => lsp_types::SymbolKind::Constant,
40 SyntaxKind::CONST_DEF => lsp_types::SymbolKind::Constant,
41 SyntaxKind::IMPL_DEF => lsp_types::SymbolKind::Object,
42 _ => lsp_types::SymbolKind::Variable,
43 }
44}
45
46pub(crate) fn document_highlight_kind(
47 reference_access: ReferenceAccess,
48) -> lsp_types::DocumentHighlightKind {
49 match reference_access {
50 ReferenceAccess::Read => lsp_types::DocumentHighlightKind::Read,
51 ReferenceAccess::Write => lsp_types::DocumentHighlightKind::Write,
52 }
53}
54
55pub(crate) fn diagnostic_severity(severity: Severity) -> lsp_types::DiagnosticSeverity {
56 match severity {
57 Severity::Error => lsp_types::DiagnosticSeverity::Error,
58 Severity::WeakWarning => lsp_types::DiagnosticSeverity::Hint,
59 }
60}
61
62pub(crate) fn documentation(documentation: Documentation) -> lsp_types::Documentation {
63 let value = crate::markdown::format_docs(documentation.as_str());
64 let markup_content = lsp_types::MarkupContent { kind: lsp_types::MarkupKind::Markdown, value };
65 lsp_types::Documentation::MarkupContent(markup_content)
66}
67
68pub(crate) fn insert_text_format(
69 insert_text_format: InsertTextFormat,
70) -> lsp_types::InsertTextFormat {
71 match insert_text_format {
72 InsertTextFormat::Snippet => lsp_types::InsertTextFormat::Snippet,
73 InsertTextFormat::PlainText => lsp_types::InsertTextFormat::PlainText,
74 }
75}
76
77pub(crate) fn completion_item_kind(
78 completion_item_kind: CompletionItemKind,
79) -> lsp_types::CompletionItemKind {
80 match completion_item_kind {
81 CompletionItemKind::Keyword => lsp_types::CompletionItemKind::Keyword,
82 CompletionItemKind::Snippet => lsp_types::CompletionItemKind::Snippet,
83 CompletionItemKind::Module => lsp_types::CompletionItemKind::Module,
84 CompletionItemKind::Function => lsp_types::CompletionItemKind::Function,
85 CompletionItemKind::Struct => lsp_types::CompletionItemKind::Struct,
86 CompletionItemKind::Enum => lsp_types::CompletionItemKind::Enum,
87 CompletionItemKind::EnumVariant => lsp_types::CompletionItemKind::EnumMember,
88 CompletionItemKind::BuiltinType => lsp_types::CompletionItemKind::Struct,
89 CompletionItemKind::Binding => lsp_types::CompletionItemKind::Variable,
90 CompletionItemKind::Field => lsp_types::CompletionItemKind::Field,
91 CompletionItemKind::Trait => lsp_types::CompletionItemKind::Interface,
92 CompletionItemKind::TypeAlias => lsp_types::CompletionItemKind::Struct,
93 CompletionItemKind::Const => lsp_types::CompletionItemKind::Constant,
94 CompletionItemKind::Static => lsp_types::CompletionItemKind::Value,
95 CompletionItemKind::Method => lsp_types::CompletionItemKind::Method,
96 CompletionItemKind::TypeParam => lsp_types::CompletionItemKind::TypeParameter,
97 CompletionItemKind::Macro => lsp_types::CompletionItemKind::Method,
98 CompletionItemKind::Attribute => lsp_types::CompletionItemKind::EnumMember,
99 }
100}
101
102pub(crate) fn text_edit(
103 line_index: &LineIndex,
104 line_endings: LineEndings,
105 indel: Indel,
106) -> lsp_types::TextEdit {
107 let range = range(line_index, indel.delete);
108 let new_text = match line_endings {
109 LineEndings::Unix => indel.insert,
110 LineEndings::Dos => indel.insert.replace('\n', "\r\n"),
111 };
112 lsp_types::TextEdit { range, new_text }
113}
114
115pub(crate) fn text_edit_vec(
116 line_index: &LineIndex,
117 line_endings: LineEndings,
118 text_edit: TextEdit,
119) -> Vec<lsp_types::TextEdit> {
120 text_edit
121 .as_indels()
122 .iter()
123 .map(|it| self::text_edit(line_index, line_endings, it.clone()))
124 .collect()
125}
126
127pub(crate) fn completion_item(
128 line_index: &LineIndex,
129 line_endings: LineEndings,
130 completion_item: CompletionItem,
131) -> lsp_types::CompletionItem {
132 let mut additional_text_edits = Vec::new();
133 let mut text_edit = None;
134 // LSP does not allow arbitrary edits in completion, so we have to do a
135 // non-trivial mapping here.
136 let source_range = completion_item.source_range();
137 for indel in completion_item.text_edit().as_indels() {
138 if indel.delete.contains_range(source_range) {
139 text_edit = Some(if indel.delete == source_range {
140 self::text_edit(line_index, line_endings, indel.clone())
141 } else {
142 assert!(source_range.end() == indel.delete.end());
143 let range1 = TextRange::new(indel.delete.start(), source_range.start());
144 let range2 = source_range;
145 let indel1 = Indel::replace(range1, String::new());
146 let indel2 = Indel::replace(range2, indel.insert.clone());
147 additional_text_edits.push(self::text_edit(line_index, line_endings, indel1));
148 self::text_edit(line_index, line_endings, indel2)
149 })
150 } else {
151 assert!(source_range.intersect(indel.delete).is_none());
152 let text_edit = self::text_edit(line_index, line_endings, indel.clone());
153 additional_text_edits.push(text_edit);
154 }
155 }
156 let text_edit = text_edit.unwrap();
157
158 let mut res = lsp_types::CompletionItem {
159 label: completion_item.label().to_string(),
160 detail: completion_item.detail().map(|it| it.to_string()),
161 filter_text: Some(completion_item.lookup().to_string()),
162 kind: completion_item.kind().map(completion_item_kind),
163 text_edit: Some(text_edit.into()),
164 additional_text_edits: Some(additional_text_edits),
165 documentation: completion_item.documentation().map(documentation),
166 deprecated: Some(completion_item.deprecated()),
167 command: if completion_item.trigger_call_info() {
168 let cmd = lsp_types::Command {
169 title: "triggerParameterHints".into(),
170 command: "editor.action.triggerParameterHints".into(),
171 arguments: None,
172 };
173 Some(cmd)
174 } else {
175 None
176 },
177 ..Default::default()
178 };
179
180 if completion_item.score().is_some() {
181 res.preselect = Some(true)
182 }
183
184 if completion_item.deprecated() {
185 res.tags = Some(vec![lsp_types::CompletionItemTag::Deprecated])
186 }
187
188 res.insert_text_format = Some(insert_text_format(completion_item.insert_text_format()));
189
190 res
191}
192
193pub(crate) fn signature_information(
194 signature: FunctionSignature,
195 concise: bool,
196) -> lsp_types::SignatureInformation {
197 let (label, documentation, params) = if concise {
198 let mut params = signature.parameters;
199 if signature.has_self_param {
200 params.remove(0);
201 }
202 (params.join(", "), None, params)
203 } else {
204 (signature.to_string(), signature.doc.map(documentation), signature.parameters)
205 };
206
207 let parameters: Vec<lsp_types::ParameterInformation> = params
208 .into_iter()
209 .map(|param| lsp_types::ParameterInformation {
210 label: lsp_types::ParameterLabel::Simple(param),
211 documentation: None,
212 })
213 .collect();
214
215 lsp_types::SignatureInformation { label, documentation, parameters: Some(parameters) }
216}
217
218pub(crate) fn inlay_int(line_index: &LineIndex, inlay_hint: InlayHint) -> lsp_ext::InlayHint {
219 lsp_ext::InlayHint {
220 label: inlay_hint.label.to_string(),
221 range: range(line_index, inlay_hint.range),
222 kind: match inlay_hint.kind {
223 InlayKind::ParameterHint => lsp_ext::InlayKind::ParameterHint,
224 InlayKind::TypeHint => lsp_ext::InlayKind::TypeHint,
225 InlayKind::ChainingHint => lsp_ext::InlayKind::ChainingHint,
226 },
227 }
228}
229
230pub(crate) fn semantic_tokens(
231 text: &str,
232 line_index: &LineIndex,
233 highlights: Vec<HighlightedRange>,
234) -> lsp_types::SemanticTokens {
235 let mut builder = semantic_tokens::SemanticTokensBuilder::default();
236
237 for highlight_range in highlights {
238 let (type_, mods) = semantic_token_type_and_modifiers(highlight_range.highlight);
239 let token_index = semantic_tokens::type_index(type_);
240 let modifier_bitset = mods.0;
241
242 for mut text_range in line_index.lines(highlight_range.range) {
243 if text[text_range].ends_with('\n') {
244 text_range =
245 TextRange::new(text_range.start(), text_range.end() - TextSize::of('\n'));
246 }
247 let range = range(&line_index, text_range);
248 builder.push(range, token_index, modifier_bitset);
249 }
250 }
251
252 builder.build()
253}
254
255fn semantic_token_type_and_modifiers(
256 highlight: Highlight,
257) -> (lsp_types::SemanticTokenType, semantic_tokens::ModifierSet) {
258 let mut mods = semantic_tokens::ModifierSet::default();
259 let type_ = match highlight.tag {
260 HighlightTag::Struct => lsp_types::SemanticTokenType::STRUCT,
261 HighlightTag::Enum => lsp_types::SemanticTokenType::ENUM,
262 HighlightTag::Union => semantic_tokens::UNION,
263 HighlightTag::TypeAlias => semantic_tokens::TYPE_ALIAS,
264 HighlightTag::Trait => lsp_types::SemanticTokenType::INTERFACE,
265 HighlightTag::BuiltinType => semantic_tokens::BUILTIN_TYPE,
266 HighlightTag::SelfType => lsp_types::SemanticTokenType::TYPE,
267 HighlightTag::Field => lsp_types::SemanticTokenType::PROPERTY,
268 HighlightTag::Function => lsp_types::SemanticTokenType::FUNCTION,
269 HighlightTag::Module => lsp_types::SemanticTokenType::NAMESPACE,
270 HighlightTag::Constant => {
271 mods |= semantic_tokens::CONSTANT;
272 mods |= lsp_types::SemanticTokenModifier::STATIC;
273 lsp_types::SemanticTokenType::VARIABLE
274 }
275 HighlightTag::Static => {
276 mods |= lsp_types::SemanticTokenModifier::STATIC;
277 lsp_types::SemanticTokenType::VARIABLE
278 }
279 HighlightTag::EnumVariant => semantic_tokens::ENUM_MEMBER,
280 HighlightTag::Macro => lsp_types::SemanticTokenType::MACRO,
281 HighlightTag::Local => lsp_types::SemanticTokenType::VARIABLE,
282 HighlightTag::TypeParam => lsp_types::SemanticTokenType::TYPE_PARAMETER,
283 HighlightTag::Lifetime => semantic_tokens::LIFETIME,
284 HighlightTag::ByteLiteral | HighlightTag::NumericLiteral => {
285 lsp_types::SemanticTokenType::NUMBER
286 }
287 HighlightTag::CharLiteral | HighlightTag::StringLiteral => {
288 lsp_types::SemanticTokenType::STRING
289 }
290 HighlightTag::Comment => lsp_types::SemanticTokenType::COMMENT,
291 HighlightTag::Attribute => semantic_tokens::ATTRIBUTE,
292 HighlightTag::Keyword => lsp_types::SemanticTokenType::KEYWORD,
293 HighlightTag::UnresolvedReference => semantic_tokens::UNRESOLVED_REFERENCE,
294 HighlightTag::FormatSpecifier => semantic_tokens::FORMAT_SPECIFIER,
295 };
296
297 for modifier in highlight.modifiers.iter() {
298 let modifier = match modifier {
299 HighlightModifier::Definition => lsp_types::SemanticTokenModifier::DECLARATION,
300 HighlightModifier::ControlFlow => semantic_tokens::CONTROL_FLOW,
301 HighlightModifier::Mutable => semantic_tokens::MUTABLE,
302 HighlightModifier::Unsafe => semantic_tokens::UNSAFE,
303 };
304 mods |= modifier;
305 }
306
307 (type_, mods)
308}
309
310pub(crate) fn folding_range(
311 text: &str,
312 line_index: &LineIndex,
313 line_folding_only: bool,
314 fold: Fold,
315) -> lsp_types::FoldingRange {
316 let kind = match fold.kind {
317 FoldKind::Comment => Some(lsp_types::FoldingRangeKind::Comment),
318 FoldKind::Imports => Some(lsp_types::FoldingRangeKind::Imports),
319 FoldKind::Mods | FoldKind::Block => None,
320 };
321
322 let range = range(line_index, fold.range);
323
324 if line_folding_only {
325 // Clients with line_folding_only == true (such as VSCode) will fold the whole end line
326 // even if it contains text not in the folding range. To prevent that we exclude
327 // range.end.line from the folding region if there is more text after range.end
328 // on the same line.
329 let has_more_text_on_end_line = text[TextRange::new(fold.range.end(), TextSize::of(text))]
330 .chars()
331 .take_while(|it| *it != '\n')
332 .any(|it| !it.is_whitespace());
333
334 let end_line = if has_more_text_on_end_line {
335 range.end.line.saturating_sub(1)
336 } else {
337 range.end.line
338 };
339
340 lsp_types::FoldingRange {
341 start_line: range.start.line,
342 start_character: None,
343 end_line,
344 end_character: None,
345 kind,
346 }
347 } else {
348 lsp_types::FoldingRange {
349 start_line: range.start.line,
350 start_character: Some(range.start.character),
351 end_line: range.end.line,
352 end_character: Some(range.end.character),
353 kind,
354 }
355 }
356}
357
358pub(crate) fn url(world: &WorldSnapshot, file_id: FileId) -> Result<lsp_types::Url> {
359 world.file_id_to_uri(file_id)
360}
361
362pub(crate) fn text_document_identifier(
363 world: &WorldSnapshot,
364 file_id: FileId,
365) -> Result<lsp_types::TextDocumentIdentifier> {
366 let res = lsp_types::TextDocumentIdentifier { uri: url(world, file_id)? };
367 Ok(res)
368}
369
370pub(crate) fn versioned_text_document_identifier(
371 world: &WorldSnapshot,
372 file_id: FileId,
373 version: Option<i64>,
374) -> Result<lsp_types::VersionedTextDocumentIdentifier> {
375 let res = lsp_types::VersionedTextDocumentIdentifier { uri: url(world, file_id)?, version };
376 Ok(res)
377}
378
379pub(crate) fn location(world: &WorldSnapshot, frange: FileRange) -> Result<lsp_types::Location> {
380 let url = url(world, frange.file_id)?;
381 let line_index = world.analysis().file_line_index(frange.file_id)?;
382 let range = range(&line_index, frange.range);
383 let loc = lsp_types::Location::new(url, range);
384 Ok(loc)
385}
386
387pub(crate) fn location_link(
388 world: &WorldSnapshot,
389 src: FileRange,
390 target: NavigationTarget,
391) -> Result<lsp_types::LocationLink> {
392 let src_location = location(world, src)?;
393 let (target_uri, target_range, target_selection_range) = location_info(world, target)?;
394 let res = lsp_types::LocationLink {
395 origin_selection_range: Some(src_location.range),
396 target_uri,
397 target_range,
398 target_selection_range,
399 };
400 Ok(res)
401}
402
403fn location_info(
404 world: &WorldSnapshot,
405 target: NavigationTarget,
406) -> Result<(lsp_types::Url, lsp_types::Range, lsp_types::Range)> {
407 let line_index = world.analysis().file_line_index(target.file_id())?;
408
409 let target_uri = url(world, target.file_id())?;
410 let target_range = range(&line_index, target.full_range());
411 let target_selection_range =
412 target.focus_range().map(|it| range(&line_index, it)).unwrap_or(target_range);
413 Ok((target_uri, target_range, target_selection_range))
414}
415
416pub(crate) fn goto_definition_response(
417 world: &WorldSnapshot,
418 src: FileRange,
419 targets: Vec<NavigationTarget>,
420) -> Result<lsp_types::GotoDefinitionResponse> {
421 if world.config.client_caps.location_link {
422 let links = targets
423 .into_iter()
424 .map(|nav| location_link(world, src, nav))
425 .collect::<Result<Vec<_>>>()?;
426 Ok(links.into())
427 } else {
428 let locations = targets
429 .into_iter()
430 .map(|nav| {
431 location(
432 world,
433 FileRange {
434 file_id: nav.file_id(),
435 range: nav.focus_range().unwrap_or(nav.range()),
436 },
437 )
438 })
439 .collect::<Result<Vec<_>>>()?;
440 Ok(locations.into())
441 }
442}
443
444pub(crate) fn text_document_edit(
445 world: &WorldSnapshot,
446 source_file_edit: SourceFileEdit,
447) -> Result<lsp_types::TextDocumentEdit> {
448 let text_document = versioned_text_document_identifier(world, source_file_edit.file_id, None)?;
449 let line_index = world.analysis().file_line_index(source_file_edit.file_id)?;
450 let line_endings = world.file_line_endings(source_file_edit.file_id);
451 let edits = source_file_edit
452 .edit
453 .as_indels()
454 .iter()
455 .map(|it| text_edit(&line_index, line_endings, it.clone()))
456 .collect();
457 Ok(lsp_types::TextDocumentEdit { text_document, edits })
458}
459
460pub(crate) fn resource_op(
461 world: &WorldSnapshot,
462 file_system_edit: FileSystemEdit,
463) -> Result<lsp_types::ResourceOp> {
464 let res = match file_system_edit {
465 FileSystemEdit::CreateFile { source_root, path } => {
466 let uri = world.path_to_uri(source_root, &path)?;
467 lsp_types::ResourceOp::Create(lsp_types::CreateFile { uri, options: None })
468 }
469 FileSystemEdit::MoveFile { src, dst_source_root, dst_path } => {
470 let old_uri = world.file_id_to_uri(src)?;
471 let new_uri = world.path_to_uri(dst_source_root, &dst_path)?;
472 lsp_types::ResourceOp::Rename(lsp_types::RenameFile { old_uri, new_uri, options: None })
473 }
474 };
475 Ok(res)
476}
477
478pub(crate) fn source_change(
479 world: &WorldSnapshot,
480 source_change: SourceChange,
481) -> Result<lsp_ext::SourceChange> {
482 let cursor_position = match source_change.cursor_position {
483 None => None,
484 Some(pos) => {
485 let line_index = world.analysis().file_line_index(pos.file_id)?;
486 let edit = source_change
487 .source_file_edits
488 .iter()
489 .find(|it| it.file_id == pos.file_id)
490 .map(|it| &it.edit);
491 let line_col = match edit {
492 Some(edit) => translate_offset_with_edit(&*line_index, pos.offset, edit),
493 None => line_index.line_col(pos.offset),
494 };
495 let position =
496 lsp_types::Position::new(u64::from(line_col.line), u64::from(line_col.col_utf16));
497 Some(lsp_types::TextDocumentPositionParams {
498 text_document: text_document_identifier(world, pos.file_id)?,
499 position,
500 })
501 }
502 };
503 let mut document_changes: Vec<lsp_types::DocumentChangeOperation> = Vec::new();
504 for op in source_change.file_system_edits {
505 let op = resource_op(&world, op)?;
506 document_changes.push(lsp_types::DocumentChangeOperation::Op(op));
507 }
508 for edit in source_change.source_file_edits {
509 let edit = text_document_edit(&world, edit)?;
510 document_changes.push(lsp_types::DocumentChangeOperation::Edit(edit));
511 }
512 let workspace_edit = lsp_types::WorkspaceEdit {
513 changes: None,
514 document_changes: Some(lsp_types::DocumentChanges::Operations(document_changes)),
515 };
516 Ok(lsp_ext::SourceChange { label: source_change.label, workspace_edit, cursor_position })
517}
518
519pub fn call_hierarchy_item(
520 world: &WorldSnapshot,
521 target: NavigationTarget,
522) -> Result<lsp_types::CallHierarchyItem> {
523 let name = target.name().to_string();
524 let detail = target.description().map(|it| it.to_string());
525 let kind = symbol_kind(target.kind());
526 let (uri, range, selection_range) = location_info(world, target)?;
527 Ok(lsp_types::CallHierarchyItem { name, kind, tags: None, detail, uri, range, selection_range })
528}
529
530#[cfg(test)]
531mod tests {
532 use test_utils::extract_ranges;
533
534 use super::*;
535
536 #[test]
537 fn conv_fold_line_folding_only_fixup() {
538 let text = r#"<fold>mod a;
539mod b;
540mod c;</fold>
541
542fn main() <fold>{
543 if cond <fold>{
544 a::do_a();
545 }</fold> else <fold>{
546 b::do_b();
547 }</fold>
548}</fold>"#;
549
550 let (ranges, text) = extract_ranges(text, "fold");
551 assert_eq!(ranges.len(), 4);
552 let folds = vec![
553 Fold { range: ranges[0], kind: FoldKind::Mods },
554 Fold { range: ranges[1], kind: FoldKind::Block },
555 Fold { range: ranges[2], kind: FoldKind::Block },
556 Fold { range: ranges[3], kind: FoldKind::Block },
557 ];
558
559 let line_index = LineIndex::new(&text);
560 let converted: Vec<lsp_types::FoldingRange> =
561 folds.into_iter().map(|it| folding_range(&text, &line_index, true, it)).collect();
562
563 let expected_lines = [(0, 2), (4, 10), (5, 6), (7, 9)];
564 assert_eq!(converted.len(), expected_lines.len());
565 for (folding_range, (start_line, end_line)) in converted.iter().zip(expected_lines.iter()) {
566 assert_eq!(folding_range.start_line, *start_line);
567 assert_eq!(folding_range.start_character, None);
568 assert_eq!(folding_range.end_line, *end_line);
569 assert_eq!(folding_range.end_character, None);
570 }
571 }
572}
573
574pub(crate) fn code_action(world: &WorldSnapshot, assist: Assist) -> Result<lsp_types::CodeAction> {
575 let source_change = source_change(&world, assist.source_change)?;
576 let arg = serde_json::to_value(source_change)?;
577 let title = assist.label;
578 let command = lsp_types::Command {
579 title: title.clone(),
580 command: "rust-analyzer.applySourceChange".to_string(),
581 arguments: Some(vec![arg]),
582 };
583
584 Ok(lsp_types::CodeAction {
585 title,
586 kind: Some(String::new()),
587 diagnostics: None,
588 edit: None,
589 command: Some(command),
590 is_preferred: None,
591 })
592}
diff --git a/crates/rust-analyzer/src/world.rs b/crates/rust-analyzer/src/world.rs
index 16020648d..6333c15b2 100644
--- a/crates/rust-analyzer/src/world.rs
+++ b/crates/rust-analyzer/src/world.rs
@@ -137,15 +137,6 @@ impl WorldState {
137 opts 137 opts
138 }; 138 };
139 139
140 // Create crate graph from all the workspaces
141 let mut crate_graph = CrateGraph::default();
142 let mut load = |path: &std::path::Path| {
143 // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
144 let path = path.canonicalize().ok()?;
145 let vfs_file = vfs.load(&path);
146 vfs_file.map(|f| FileId(f.0))
147 };
148
149 let proc_macro_client = match &config.proc_macro_srv { 140 let proc_macro_client = match &config.proc_macro_srv {
150 None => ProcMacroClient::dummy(), 141 None => ProcMacroClient::dummy(),
151 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) { 142 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
@@ -161,19 +152,22 @@ impl WorldState {
161 }, 152 },
162 }; 153 };
163 154
164 workspaces 155 // Create crate graph from all the workspaces
165 .iter() 156 let mut crate_graph = CrateGraph::default();
166 .map(|ws| { 157 let mut load = |path: &Path| {
167 ws.to_crate_graph( 158 // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
168 &default_cfg_options, 159 let path = path.canonicalize().ok()?;
169 &extern_source_roots, 160 let vfs_file = vfs.load(&path);
170 &proc_macro_client, 161 vfs_file.map(|f| FileId(f.0))
171 &mut load, 162 };
172 ) 163 for ws in workspaces.iter() {
173 }) 164 crate_graph.extend(ws.to_crate_graph(
174 .for_each(|graph| { 165 &default_cfg_options,
175 crate_graph.extend(graph); 166 &extern_source_roots,
176 }); 167 &proc_macro_client,
168 &mut load,
169 ));
170 }
177 change.set_crate_graph(crate_graph); 171 change.set_crate_graph(crate_graph);
178 172
179 let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c)); 173 let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));
diff --git a/crates/rust-analyzer/tests/heavy_tests/main.rs b/crates/rust-analyzer/tests/heavy_tests/main.rs
index e459e3a3c..5011cc273 100644
--- a/crates/rust-analyzer/tests/heavy_tests/main.rs
+++ b/crates/rust-analyzer/tests/heavy_tests/main.rs
@@ -3,15 +3,16 @@ mod support;
3use std::{collections::HashMap, path::PathBuf, time::Instant}; 3use std::{collections::HashMap, path::PathBuf, time::Instant};
4 4
5use lsp_types::{ 5use lsp_types::{
6 CodeActionContext, DidOpenTextDocumentParams, DocumentFormattingParams, FormattingOptions, 6 notification::DidOpenTextDocument,
7 GotoDefinitionParams, HoverParams, PartialResultParams, Position, Range, TextDocumentItem, 7 request::{
8 TextDocumentPositionParams, WorkDoneProgressParams, 8 CodeActionRequest, Completion, Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest,
9}; 9 },
10use rust_analyzer::req::{ 10 CodeActionContext, CodeActionParams, CompletionParams, DidOpenTextDocumentParams,
11 CodeActionParams, CodeActionRequest, Completion, CompletionParams, DidOpenTextDocument, 11 DocumentFormattingParams, FormattingOptions, GotoDefinitionParams, HoverParams,
12 Formatting, GotoDefinition, GotoTypeDefinition, HoverRequest, OnEnter, Runnables, 12 PartialResultParams, Position, Range, TextDocumentItem, TextDocumentPositionParams,
13 RunnablesParams, 13 WorkDoneProgressParams,
14}; 14};
15use rust_analyzer::lsp_ext::{OnEnter, Runnables, RunnablesParams};
15use serde_json::json; 16use serde_json::json;
16use tempfile::TempDir; 17use tempfile::TempDir;
17use test_utils::skip_slow_tests; 18use test_utils::skip_slow_tests;
diff --git a/crates/rust-analyzer/tests/heavy_tests/support.rs b/crates/rust-analyzer/tests/heavy_tests/support.rs
index 8d47ee4f6..9acbae066 100644
--- a/crates/rust-analyzer/tests/heavy_tests/support.rs
+++ b/crates/rust-analyzer/tests/heavy_tests/support.rs
@@ -13,15 +13,15 @@ use lsp_types::{
13 request::Shutdown, 13 request::Shutdown,
14 DidOpenTextDocumentParams, TextDocumentIdentifier, TextDocumentItem, Url, WorkDoneProgress, 14 DidOpenTextDocumentParams, TextDocumentIdentifier, TextDocumentItem, Url, WorkDoneProgress,
15}; 15};
16use lsp_types::{ProgressParams, ProgressParamsValue};
16use serde::Serialize; 17use serde::Serialize;
17use serde_json::{to_string_pretty, Value}; 18use serde_json::{to_string_pretty, Value};
18use tempfile::TempDir; 19use tempfile::TempDir;
19use test_utils::{find_mismatch, parse_fixture}; 20use test_utils::{find_mismatch, parse_fixture};
20 21
21use req::{ProgressParams, ProgressParamsValue};
22use rust_analyzer::{ 22use rust_analyzer::{
23 config::{ClientCapsConfig, Config}, 23 config::{ClientCapsConfig, Config},
24 main_loop, req, 24 main_loop,
25}; 25};
26 26
27pub struct Project<'a> { 27pub struct Project<'a> {
@@ -80,6 +80,7 @@ impl<'a> Project<'a> {
80 client_caps: ClientCapsConfig { 80 client_caps: ClientCapsConfig {
81 location_link: true, 81 location_link: true,
82 code_action_literals: true, 82 code_action_literals: true,
83 work_done_progress: true,
83 ..Default::default() 84 ..Default::default()
84 }, 85 },
85 with_sysroot: self.with_sysroot, 86 with_sysroot: self.with_sysroot,
@@ -206,7 +207,7 @@ impl Server {
206 Message::Notification(n) if n.method == "$/progress" => { 207 Message::Notification(n) if n.method == "$/progress" => {
207 match n.clone().extract::<ProgressParams>("$/progress").unwrap() { 208 match n.clone().extract::<ProgressParams>("$/progress").unwrap() {
208 ProgressParams { 209 ProgressParams {
209 token: req::ProgressToken::String(ref token), 210 token: lsp_types::ProgressToken::String(ref token),
210 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(_)), 211 value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(_)),
211 } if token == "rustAnalyzer/startup" => true, 212 } if token == "rustAnalyzer/startup" => true,
212 _ => false, 213 _ => false,