aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--crates/ra_hir/src/docs.rs7
-rw-r--r--crates/ra_hir/src/expr.rs16
-rw-r--r--crates/ra_hir/src/marks.rs2
-rw-r--r--crates/ra_hir/src/ty.rs37
-rw-r--r--crates/ra_hir/src/ty/snapshots/tests__infer_in_elseif.snap17
-rw-r--r--crates/ra_hir/src/ty/snapshots/tests__recursive_vars.snap14
-rw-r--r--crates/ra_hir/src/ty/snapshots/tests__recursive_vars_2.snap21
-rw-r--r--crates/ra_hir/src/ty/tests.rs49
-rw-r--r--crates/ra_ide_api/src/call_info.rs25
-rw-r--r--crates/ra_ide_api/src/hover.rs7
-rw-r--r--crates/ra_ide_api/src/marks.rs1
-rw-r--r--crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs5
-rw-r--r--crates/ra_lsp_server/src/main_loop/handlers.rs28
-rw-r--r--crates/ra_lsp_server/src/project_model/cargo_workspace.rs10
-rw-r--r--crates/ra_syntax/src/ast.rs93
-rw-r--r--crates/tools/src/bin/pre-commit.rs7
-rw-r--r--crates/tools/src/lib.rs106
-rw-r--r--crates/tools/src/main.rs127
-rw-r--r--crates/tools/tests/cli.rs16
20 files changed, 401 insertions, 189 deletions
diff --git a/.travis.yml b/.travis.yml
index bddf1bebb..8d10a43f0 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,8 +10,6 @@ build: &rust_build
10 script: 10 script:
11 - rustup component add rustfmt 11 - rustup component add rustfmt
12 - rustup component add rust-src 12 - rustup component add rust-src
13 - cargo gen-tests --verify
14 - cargo gen-syntax --verify
15 - cargo test --no-run # let's measure compile time separately 13 - cargo test --no-run # let's measure compile time separately
16 - cargo test 14 - cargo test
17 env: 15 env:
diff --git a/crates/ra_hir/src/docs.rs b/crates/ra_hir/src/docs.rs
index b1b47af9e..5db72c08a 100644
--- a/crates/ra_hir/src/docs.rs
+++ b/crates/ra_hir/src/docs.rs
@@ -27,10 +27,5 @@ pub trait Docs {
27} 27}
28 28
29pub(crate) fn docs_from_ast(node: &impl ast::DocCommentsOwner) -> Option<Documentation> { 29pub(crate) fn docs_from_ast(node: &impl ast::DocCommentsOwner) -> Option<Documentation> {
30 let comments = node.doc_comment_text(); 30 node.doc_comment_text().map(|it| Documentation::new(&it))
31 if comments.is_empty() {
32 None
33 } else {
34 Some(Documentation::new(&comments))
35 }
36} 31}
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs
index 29469af2c..60d997bbe 100644
--- a/crates/ra_hir/src/expr.rs
+++ b/crates/ra_hir/src/expr.rs
@@ -498,7 +498,13 @@ impl ExprCollector {
498 let then_branch = self.collect_block_opt(e.then_branch()); 498 let then_branch = self.collect_block_opt(e.then_branch());
499 let else_branch = e 499 let else_branch = e
500 .else_branch() 500 .else_branch()
501 .map(|e| self.collect_block(e)) 501 .map(|b| match b {
502 ast::ElseBranchFlavor::Block(it) => self.collect_block(it),
503 ast::ElseBranchFlavor::IfExpr(elif) => {
504 let expr: &ast::Expr = ast::Expr::cast(elif.syntax()).unwrap();
505 self.collect_expr(expr)
506 }
507 })
502 .unwrap_or_else(|| self.empty_block()); 508 .unwrap_or_else(|| self.empty_block());
503 let placeholder_pat = self.pats.alloc(Pat::Missing); 509 let placeholder_pat = self.pats.alloc(Pat::Missing);
504 let arms = vec![ 510 let arms = vec![
@@ -521,7 +527,13 @@ impl ExprCollector {
521 } else { 527 } else {
522 let condition = self.collect_expr_opt(e.condition().and_then(|c| c.expr())); 528 let condition = self.collect_expr_opt(e.condition().and_then(|c| c.expr()));
523 let then_branch = self.collect_block_opt(e.then_branch()); 529 let then_branch = self.collect_block_opt(e.then_branch());
524 let else_branch = e.else_branch().map(|e| self.collect_block(e)); 530 let else_branch = e.else_branch().map(|b| match b {
531 ast::ElseBranchFlavor::Block(it) => self.collect_block(it),
532 ast::ElseBranchFlavor::IfExpr(elif) => {
533 let expr: &ast::Expr = ast::Expr::cast(elif.syntax()).unwrap();
534 self.collect_expr(expr)
535 }
536 });
525 self.alloc_expr( 537 self.alloc_expr(
526 Expr::If { 538 Expr::If {
527 condition, 539 condition,
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs
index 338ed0516..d704c3adb 100644
--- a/crates/ra_hir/src/marks.rs
+++ b/crates/ra_hir/src/marks.rs
@@ -1,4 +1,6 @@
1test_utils::marks!( 1test_utils::marks!(
2 name_res_works_for_broken_modules 2 name_res_works_for_broken_modules
3 item_map_enum_importing 3 item_map_enum_importing
4 type_var_cycles_resolve_completely
5 type_var_cycles_resolve_as_possible
4); 6);
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index 179ebddee..31ea45706 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -29,6 +29,8 @@ use ra_arena::map::ArenaMap;
29use join_to_string::join; 29use join_to_string::join;
30use rustc_hash::FxHashMap; 30use rustc_hash::FxHashMap;
31 31
32use test_utils::tested_by;
33
32use crate::{ 34use crate::{
33 Module, Function, Struct, StructField, Enum, EnumVariant, Path, Name, ImplBlock, 35 Module, Function, Struct, StructField, Enum, EnumVariant, Path, Name, ImplBlock,
34 FnSignature, FnScopes, ModuleDef, AdtDef, 36 FnSignature, FnScopes, ModuleDef, AdtDef,
@@ -862,14 +864,15 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
862 } 864 }
863 865
864 fn resolve_all(mut self) -> InferenceResult { 866 fn resolve_all(mut self) -> InferenceResult {
867 let mut tv_stack = Vec::new();
865 let mut expr_types = mem::replace(&mut self.type_of_expr, ArenaMap::default()); 868 let mut expr_types = mem::replace(&mut self.type_of_expr, ArenaMap::default());
866 for ty in expr_types.values_mut() { 869 for ty in expr_types.values_mut() {
867 let resolved = self.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 870 let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown));
868 *ty = resolved; 871 *ty = resolved;
869 } 872 }
870 let mut pat_types = mem::replace(&mut self.type_of_pat, ArenaMap::default()); 873 let mut pat_types = mem::replace(&mut self.type_of_pat, ArenaMap::default());
871 for ty in pat_types.values_mut() { 874 for ty in pat_types.values_mut() {
872 let resolved = self.resolve_ty_completely(mem::replace(ty, Ty::Unknown)); 875 let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown));
873 *ty = resolved; 876 *ty = resolved;
874 } 877 }
875 InferenceResult { 878 InferenceResult {
@@ -1014,13 +1017,21 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1014 /// by their known types. All types returned by the infer_* functions should 1017 /// by their known types. All types returned by the infer_* functions should
1015 /// be resolved as far as possible, i.e. contain no type variables with 1018 /// be resolved as far as possible, i.e. contain no type variables with
1016 /// known type. 1019 /// known type.
1017 fn resolve_ty_as_possible(&mut self, ty: Ty) -> Ty { 1020 fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
1018 ty.fold(&mut |ty| match ty { 1021 ty.fold(&mut |ty| match ty {
1019 Ty::Infer(tv) => { 1022 Ty::Infer(tv) => {
1020 let inner = tv.to_inner(); 1023 let inner = tv.to_inner();
1024 if tv_stack.contains(&inner) {
1025 tested_by!(type_var_cycles_resolve_as_possible);
1026 // recursive type
1027 return tv.fallback_value();
1028 }
1021 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { 1029 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() {
1022 // known_ty may contain other variables that are known by now 1030 // known_ty may contain other variables that are known by now
1023 self.resolve_ty_as_possible(known_ty.clone()) 1031 tv_stack.push(inner);
1032 let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone());
1033 tv_stack.pop();
1034 result
1024 } else { 1035 } else {
1025 ty 1036 ty
1026 } 1037 }
@@ -1049,13 +1060,21 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1049 1060
1050 /// Resolves the type completely; type variables without known type are 1061 /// Resolves the type completely; type variables without known type are
1051 /// replaced by Ty::Unknown. 1062 /// replaced by Ty::Unknown.
1052 fn resolve_ty_completely(&mut self, ty: Ty) -> Ty { 1063 fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty {
1053 ty.fold(&mut |ty| match ty { 1064 ty.fold(&mut |ty| match ty {
1054 Ty::Infer(tv) => { 1065 Ty::Infer(tv) => {
1055 let inner = tv.to_inner(); 1066 let inner = tv.to_inner();
1067 if tv_stack.contains(&inner) {
1068 tested_by!(type_var_cycles_resolve_completely);
1069 // recursive type
1070 return tv.fallback_value();
1071 }
1056 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { 1072 if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() {
1057 // known_ty may contain other variables that are known by now 1073 // known_ty may contain other variables that are known by now
1058 self.resolve_ty_completely(known_ty.clone()) 1074 tv_stack.push(inner);
1075 let result = self.resolve_ty_completely(tv_stack, known_ty.clone());
1076 tv_stack.pop();
1077 result
1059 } else { 1078 } else {
1060 tv.fallback_value() 1079 tv.fallback_value()
1061 } 1080 }
@@ -1070,7 +1089,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1070 let name = path.as_ident().cloned().unwrap_or_else(Name::self_param); 1089 let name = path.as_ident().cloned().unwrap_or_else(Name::self_param);
1071 if let Some(scope_entry) = self.scopes.resolve_local_name(expr, name) { 1090 if let Some(scope_entry) = self.scopes.resolve_local_name(expr, name) {
1072 let ty = self.type_of_pat.get(scope_entry.pat())?; 1091 let ty = self.type_of_pat.get(scope_entry.pat())?;
1073 let ty = self.resolve_ty_as_possible(ty.clone()); 1092 let ty = self.resolve_ty_as_possible(&mut vec![], ty.clone());
1074 return Some(ty); 1093 return Some(ty);
1075 }; 1094 };
1076 }; 1095 };
@@ -1239,7 +1258,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1239 // use a new type variable if we got Ty::Unknown here 1258 // use a new type variable if we got Ty::Unknown here
1240 let ty = self.insert_type_vars_shallow(ty); 1259 let ty = self.insert_type_vars_shallow(ty);
1241 self.unify(&ty, expected); 1260 self.unify(&ty, expected);
1242 let ty = self.resolve_ty_as_possible(ty); 1261 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
1243 self.write_pat_ty(pat, ty.clone()); 1262 self.write_pat_ty(pat, ty.clone());
1244 ty 1263 ty
1245 } 1264 }
@@ -1538,7 +1557,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
1538 // use a new type variable if we got Ty::Unknown here 1557 // use a new type variable if we got Ty::Unknown here
1539 let ty = self.insert_type_vars_shallow(ty); 1558 let ty = self.insert_type_vars_shallow(ty);
1540 self.unify(&ty, &expected.ty); 1559 self.unify(&ty, &expected.ty);
1541 let ty = self.resolve_ty_as_possible(ty); 1560 let ty = self.resolve_ty_as_possible(&mut vec![], ty);
1542 self.write_expr_ty(tgt_expr, ty.clone()); 1561 self.write_expr_ty(tgt_expr, ty.clone());
1543 ty 1562 ty
1544 } 1563 }
diff --git a/crates/ra_hir/src/ty/snapshots/tests__infer_in_elseif.snap b/crates/ra_hir/src/ty/snapshots/tests__infer_in_elseif.snap
new file mode 100644
index 000000000..6a435e5cf
--- /dev/null
+++ b/crates/ra_hir/src/ty/snapshots/tests__infer_in_elseif.snap
@@ -0,0 +1,17 @@
1---
2created: "2019-01-26T21:36:52.714121185+00:00"
3creator: [email protected]
4expression: "&result"
5source: crates/ra_hir/src/ty/tests.rs
6---
7[35; 38) 'foo': Foo
8[45; 109) '{ ... } }': ()
9[51; 107) 'if tru... }': ()
10[54; 58) 'true': bool
11[59; 67) '{ }': ()
12[73; 107) 'if fal... }': i32
13[76; 81) 'false': bool
14[82; 107) '{ ... }': i32
15[92; 95) 'foo': Foo
16[92; 101) 'foo.field': i32
17
diff --git a/crates/ra_hir/src/ty/snapshots/tests__recursive_vars.snap b/crates/ra_hir/src/ty/snapshots/tests__recursive_vars.snap
new file mode 100644
index 000000000..c3227ff7e
--- /dev/null
+++ b/crates/ra_hir/src/ty/snapshots/tests__recursive_vars.snap
@@ -0,0 +1,14 @@
1---
2created: "2019-01-26T22:42:22.329980185+00:00"
3creator: [email protected]
4expression: "&result"
5source: crates/ra_hir/src/ty/tests.rs
6---
7[11; 48) '{ ...&y]; }': ()
8[21; 22) 'y': &[unknown]
9[25; 32) 'unknown': &[unknown]
10[38; 45) '[y, &y]': [&&[unknown]]
11[39; 40) 'y': &[unknown]
12[42; 44) '&y': &&[unknown]
13[43; 44) 'y': &[unknown]
14
diff --git a/crates/ra_hir/src/ty/snapshots/tests__recursive_vars_2.snap b/crates/ra_hir/src/ty/snapshots/tests__recursive_vars_2.snap
new file mode 100644
index 000000000..de124da5b
--- /dev/null
+++ b/crates/ra_hir/src/ty/snapshots/tests__recursive_vars_2.snap
@@ -0,0 +1,21 @@
1---
2created: "2019-01-26T22:42:22.331805845+00:00"
3creator: [email protected]
4expression: "&result"
5source: crates/ra_hir/src/ty/tests.rs
6---
7[11; 80) '{ ...x)]; }': ()
8[21; 22) 'x': &&[unknown]
9[25; 32) 'unknown': &&[unknown]
10[42; 43) 'y': &&[unknown]
11[46; 53) 'unknown': &&[unknown]
12[59; 77) '[(x, y..., &x)]': [(&&[unknown], &&[unknown])]
13[60; 66) '(x, y)': (&&[unknown], &&[unknown])
14[61; 62) 'x': &&[unknown]
15[64; 65) 'y': &&[unknown]
16[68; 76) '(&y, &x)': (&&&[unknown], &&&[unknown])
17[69; 71) '&y': &&&[unknown]
18[70; 71) 'y': &&[unknown]
19[73; 75) '&x': &&&[unknown]
20[74; 75) 'x': &&[unknown]
21
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs
index e0b0689f8..f74d6f5ea 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir/src/ty/tests.rs
@@ -3,6 +3,7 @@ use std::fmt::Write;
3 3
4use ra_db::{SourceDatabase, salsa::Database}; 4use ra_db::{SourceDatabase, salsa::Database};
5use ra_syntax::ast::{self, AstNode}; 5use ra_syntax::ast::{self, AstNode};
6use test_utils::covers;
6 7
7use crate::{ 8use crate::{
8 source_binder, 9 source_binder,
@@ -285,6 +286,23 @@ fn test() {
285} 286}
286 287
287#[test] 288#[test]
289fn infer_in_elseif() {
290 check_inference(
291 "infer_in_elseif",
292 r#"
293struct Foo { field: i32 }
294fn main(foo: Foo) {
295 if true {
296
297 } else if false {
298 foo.field
299 }
300}
301"#,
302 )
303}
304
305#[test]
288fn infer_inherent_method() { 306fn infer_inherent_method() {
289 check_inference( 307 check_inference(
290 "infer_inherent_method", 308 "infer_inherent_method",
@@ -545,6 +563,37 @@ fn quux() {
545 ); 563 );
546} 564}
547 565
566#[test]
567fn recursive_vars() {
568 covers!(type_var_cycles_resolve_completely);
569 covers!(type_var_cycles_resolve_as_possible);
570 check_inference(
571 "recursive_vars",
572 r#"
573fn test() {
574 let y = unknown;
575 [y, &y];
576}
577"#,
578 );
579}
580
581#[test]
582fn recursive_vars_2() {
583 covers!(type_var_cycles_resolve_completely);
584 covers!(type_var_cycles_resolve_as_possible);
585 check_inference(
586 "recursive_vars_2",
587 r#"
588fn test() {
589 let x = unknown;
590 let y = unknown;
591 [(x, y), (&y, &x)];
592}
593"#,
594 );
595}
596
548fn infer(content: &str) -> String { 597fn infer(content: &str) -> String {
549 let (db, _, file_id) = MockDatabase::with_single_file(content); 598 let (db, _, file_id) = MockDatabase::with_single_file(content);
550 let source_file = db.parse(file_id); 599 let source_file = db.parse(file_id);
diff --git a/crates/ra_ide_api/src/call_info.rs b/crates/ra_ide_api/src/call_info.rs
index 3267fff96..ee1e13799 100644
--- a/crates/ra_ide_api/src/call_info.rs
+++ b/crates/ra_ide_api/src/call_info.rs
@@ -1,3 +1,4 @@
1use test_utils::tested_by;
1use ra_db::SourceDatabase; 2use ra_db::SourceDatabase;
2use ra_syntax::{ 3use ra_syntax::{
3 AstNode, SyntaxNode, TextUnit, TextRange, 4 AstNode, SyntaxNode, TextUnit, TextRange,
@@ -41,7 +42,12 @@ pub(crate) fn call_info(db: &RootDatabase, position: FilePosition) -> Option<Cal
41 // where offset is in that list (or beyond). 42 // where offset is in that list (or beyond).
42 // Revisit this after we get documentation comments in. 43 // Revisit this after we get documentation comments in.
43 if let Some(ref arg_list) = calling_node.arg_list() { 44 if let Some(ref arg_list) = calling_node.arg_list() {
44 let start = arg_list.syntax().range().start(); 45 let arg_list_range = arg_list.syntax().range();
46 if !arg_list_range.contains_inclusive(position.offset) {
47 tested_by!(call_info_bad_offset);
48 return None;
49 }
50 let start = arg_list_range.start();
45 51
46 let range_search = TextRange::from_to(start, position.offset); 52 let range_search = TextRange::from_to(start, position.offset);
47 let mut commas: usize = arg_list 53 let mut commas: usize = arg_list
@@ -120,8 +126,7 @@ impl CallInfo {
120 }; 126 };
121 127
122 let mut doc = None; 128 let mut doc = None;
123 let docs = node.doc_comment_text(); 129 if let Some(docs) = node.doc_comment_text() {
124 if !docs.is_empty() {
125 // Massage markdown 130 // Massage markdown
126 let mut processed_lines = Vec::new(); 131 let mut processed_lines = Vec::new();
127 let mut in_code_block = false; 132 let mut in_code_block = false;
@@ -172,10 +177,12 @@ fn param_list(node: &ast::FnDef) -> Vec<String> {
172 177
173#[cfg(test)] 178#[cfg(test)]
174mod tests { 179mod tests {
175 use super::*; 180 use test_utils::covers;
176 181
177 use crate::mock_analysis::single_file_with_position; 182 use crate::mock_analysis::single_file_with_position;
178 183
184 use super::*;
185
179 fn call_info(text: &str) -> CallInfo { 186 fn call_info(text: &str) -> CallInfo {
180 let (analysis, position) = single_file_with_position(text); 187 let (analysis, position) = single_file_with_position(text);
181 analysis.call_info(position).unwrap().unwrap() 188 analysis.call_info(position).unwrap().unwrap()
@@ -417,4 +424,14 @@ By default this method stops actor's `Context`."#
417 ); 424 );
418 } 425 }
419 426
427 #[test]
428 fn call_info_bad_offset() {
429 covers!(call_info_bad_offset);
430 let (analysis, position) = single_file_with_position(
431 r#"fn foo(x: u32, y: u32) -> u32 {x + y}
432 fn bar() { foo <|> (3, ); }"#,
433 );
434 let call_info = analysis.call_info(position).unwrap();
435 assert!(call_info.is_none());
436 }
420} 437}
diff --git a/crates/ra_ide_api/src/hover.rs b/crates/ra_ide_api/src/hover.rs
index ff9ae2d9c..f993a461c 100644
--- a/crates/ra_ide_api/src/hover.rs
+++ b/crates/ra_ide_api/src/hover.rs
@@ -100,12 +100,7 @@ impl NavigationTarget {
100 fn docs(&self, db: &RootDatabase) -> Option<String> { 100 fn docs(&self, db: &RootDatabase) -> Option<String> {
101 let node = self.node(db)?; 101 let node = self.node(db)?;
102 fn doc_comments<N: ast::DocCommentsOwner>(node: &N) -> Option<String> { 102 fn doc_comments<N: ast::DocCommentsOwner>(node: &N) -> Option<String> {
103 let comments = node.doc_comment_text(); 103 node.doc_comment_text()
104 if comments.is_empty() {
105 None
106 } else {
107 Some(comments)
108 }
109 } 104 }
110 105
111 visitor() 106 visitor()
diff --git a/crates/ra_ide_api/src/marks.rs b/crates/ra_ide_api/src/marks.rs
index e33bf6c91..21ce7289d 100644
--- a/crates/ra_ide_api/src/marks.rs
+++ b/crates/ra_ide_api/src/marks.rs
@@ -2,4 +2,5 @@ test_utils::marks!(
2 inserts_parens_for_function_calls 2 inserts_parens_for_function_calls
3 goto_definition_works_for_methods 3 goto_definition_works_for_methods
4 goto_definition_works_for_fields 4 goto_definition_works_for_fields
5 call_info_bad_offset
5); 6);
diff --git a/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs b/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
index d64c34d54..71880b919 100644
--- a/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
+++ b/crates/ra_ide_api_light/src/assists/replace_if_let_with_match.rs
@@ -11,7 +11,10 @@ pub fn replace_if_let_with_match(ctx: AssistCtx) -> Option<Assist> {
11 let pat = cond.pat()?; 11 let pat = cond.pat()?;
12 let expr = cond.expr()?; 12 let expr = cond.expr()?;
13 let then_block = if_expr.then_branch()?; 13 let then_block = if_expr.then_branch()?;
14 let else_block = if_expr.else_branch()?; 14 let else_block = match if_expr.else_branch()? {
15 ast::ElseBranchFlavor::Block(it) => it,
16 ast::ElseBranchFlavor::IfExpr(_) => return None,
17 };
15 18
16 ctx.build("replace with match", |edit| { 19 ctx.build("replace with match", |edit| {
17 let match_expr = build_match_expr(expr, pat, then_block, else_block); 20 let match_expr = build_match_expr(expr, pat, then_block, else_block);
diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs
index 8ea9edc84..ace3da020 100644
--- a/crates/ra_lsp_server/src/main_loop/handlers.rs
+++ b/crates/ra_lsp_server/src/main_loop/handlers.rs
@@ -520,21 +520,33 @@ pub fn handle_formatting(
520 let end_position = TextUnit::of_str(&file).conv_with(&file_line_index); 520 let end_position = TextUnit::of_str(&file).conv_with(&file_line_index);
521 521
522 use std::process; 522 use std::process;
523 let mut rustfmt = process::Command::new("rustfmt") 523 let mut rustfmt = process::Command::new("rustfmt");
524 rustfmt
524 .stdin(process::Stdio::piped()) 525 .stdin(process::Stdio::piped())
525 .stdout(process::Stdio::piped()) 526 .stdout(process::Stdio::piped());
526 .spawn()?; 527
528 if let Ok(path) = params.text_document.uri.to_file_path() {
529 if let Some(parent) = path.parent() {
530 rustfmt.current_dir(parent);
531 }
532 }
533 let mut rustfmt = rustfmt.spawn()?;
527 534
528 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?; 535 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
529 536
530 let output = rustfmt.wait_with_output()?; 537 let output = rustfmt.wait_with_output()?;
531 let captured_stdout = String::from_utf8(output.stdout)?; 538 let captured_stdout = String::from_utf8(output.stdout)?;
532 if !output.status.success() { 539 if !output.status.success() {
533 failure::bail!( 540 return Err(LspError::new(
534 "rustfmt exited with error code {}: {}.", 541 -32900,
535 output.status, 542 format!(
536 captured_stdout, 543 r#"rustfmt exited with:
537 ); 544 Status: {}
545 stdout: {}"#,
546 output.status, captured_stdout,
547 ),
548 )
549 .into());
538 } 550 }
539 551
540 Ok(Some(vec![TextEdit { 552 Ok(Some(vec![TextEdit {
diff --git a/crates/ra_lsp_server/src/project_model/cargo_workspace.rs b/crates/ra_lsp_server/src/project_model/cargo_workspace.rs
index 75ae78bca..8cf99d586 100644
--- a/crates/ra_lsp_server/src/project_model/cargo_workspace.rs
+++ b/crates/ra_lsp_server/src/project_model/cargo_workspace.rs
@@ -117,9 +117,13 @@ impl Target {
117 117
118impl CargoWorkspace { 118impl CargoWorkspace {
119 pub fn from_cargo_metadata(cargo_toml: &Path) -> Result<CargoWorkspace> { 119 pub fn from_cargo_metadata(cargo_toml: &Path) -> Result<CargoWorkspace> {
120 let meta = MetadataCommand::new() 120 let mut meta = MetadataCommand::new();
121 .manifest_path(cargo_toml) 121 meta.manifest_path(cargo_toml)
122 .features(CargoOpt::AllFeatures) 122 .features(CargoOpt::AllFeatures);
123 if let Some(parent) = cargo_toml.parent() {
124 meta.current_dir(parent);
125 }
126 let meta = meta
123 .exec() 127 .exec()
124 .map_err(|e| format_err!("cargo metadata failed: {}", e))?; 128 .map_err(|e| format_err!("cargo metadata failed: {}", e))?;
125 let mut pkg_by_id = FxHashMap::default(); 129 let mut pkg_by_id = FxHashMap::default();
diff --git a/crates/ra_syntax/src/ast.rs b/crates/ra_syntax/src/ast.rs
index 00c60ebf3..3d22a88f3 100644
--- a/crates/ra_syntax/src/ast.rs
+++ b/crates/ra_syntax/src/ast.rs
@@ -115,21 +115,38 @@ pub trait DocCommentsOwner: AstNode {
115 } 115 }
116 116
117 /// Returns the textual content of a doc comment block as a single string. 117 /// Returns the textual content of a doc comment block as a single string.
118 /// That is, strips leading `///` and joins lines 118 /// That is, strips leading `///` (+ optional 1 character of whitespace)
119 fn doc_comment_text(&self) -> std::string::String { 119 /// and joins lines.
120 self.doc_comments() 120 fn doc_comment_text(&self) -> Option<std::string::String> {
121 let docs = self
122 .doc_comments()
121 .filter(|comment| comment.is_doc_comment()) 123 .filter(|comment| comment.is_doc_comment())
122 .map(|comment| { 124 .map(|comment| {
123 let prefix = comment.prefix(); 125 let prefix_len = comment.prefix().len();
124 let trimmed = comment 126
125 .text() 127 let line = comment.text().as_str();
126 .as_str() 128
127 .trim() 129 // Determine if the prefix or prefix + 1 char is stripped
128 .trim_start_matches(prefix) 130 let pos = if line
129 .trim_start(); 131 .chars()
130 trimmed.to_owned() 132 .nth(prefix_len)
133 .map(|c| c.is_whitespace())
134 .unwrap_or(false)
135 {
136 prefix_len + 1
137 } else {
138 prefix_len
139 };
140
141 line[pos..].to_owned()
131 }) 142 })
132 .join("\n") 143 .join("\n");
144
145 if docs.is_empty() {
146 None
147 } else {
148 Some(docs)
149 }
133 } 150 }
134} 151}
135 152
@@ -285,13 +302,27 @@ impl LetStmt {
285 } 302 }
286} 303}
287 304
305#[derive(Debug, Clone, PartialEq, Eq)]
306pub enum ElseBranchFlavor<'a> {
307 Block(&'a Block),
308 IfExpr(&'a IfExpr),
309}
310
288impl IfExpr { 311impl IfExpr {
289 pub fn then_branch(&self) -> Option<&Block> { 312 pub fn then_branch(&self) -> Option<&Block> {
290 self.blocks().nth(0) 313 self.blocks().nth(0)
291 } 314 }
292 pub fn else_branch(&self) -> Option<&Block> { 315 pub fn else_branch(&self) -> Option<ElseBranchFlavor> {
293 self.blocks().nth(1) 316 let res = match self.blocks().nth(1) {
317 Some(block) => ElseBranchFlavor::Block(block),
318 None => {
319 let elif: &IfExpr = child_opt(self)?;
320 ElseBranchFlavor::IfExpr(elif)
321 }
322 };
323 Some(res)
294 } 324 }
325
295 fn blocks(&self) -> AstChildren<Block> { 326 fn blocks(&self) -> AstChildren<Block> {
296 children(self) 327 children(self)
297 } 328 }
@@ -690,6 +721,18 @@ impl BindPat {
690} 721}
691 722
692#[test] 723#[test]
724fn test_doc_comment_none() {
725 let file = SourceFile::parse(
726 r#"
727 // non-doc
728 mod foo {}
729 "#,
730 );
731 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
732 assert!(module.doc_comment_text().is_none());
733}
734
735#[test]
693fn test_doc_comment_of_items() { 736fn test_doc_comment_of_items() {
694 let file = SourceFile::parse( 737 let file = SourceFile::parse(
695 r#" 738 r#"
@@ -699,5 +742,25 @@ fn test_doc_comment_of_items() {
699 "#, 742 "#,
700 ); 743 );
701 let module = file.syntax().descendants().find_map(Module::cast).unwrap(); 744 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
702 assert_eq!("doc", module.doc_comment_text()); 745 assert_eq!("doc", module.doc_comment_text().unwrap());
746}
747
748#[test]
749fn test_doc_comment_preserves_indents() {
750 let file = SourceFile::parse(
751 r#"
752 /// doc1
753 /// ```
754 /// fn foo() {
755 /// // ...
756 /// }
757 /// ```
758 mod foo {}
759 "#,
760 );
761 let module = file.syntax().descendants().find_map(Module::cast).unwrap();
762 assert_eq!(
763 "doc1\n```\nfn foo() {\n // ...\n}\n```",
764 module.doc_comment_text().unwrap()
765 );
703} 766}
diff --git a/crates/tools/src/bin/pre-commit.rs b/crates/tools/src/bin/pre-commit.rs
index bae3b26d3..e00bd0d3d 100644
--- a/crates/tools/src/bin/pre-commit.rs
+++ b/crates/tools/src/bin/pre-commit.rs
@@ -1,10 +1,9 @@
1use std::{ 1use std::process::Command;
2 process::{Command},
3};
4 2
5use tools::{Result, run_rustfmt, run, project_root};
6use failure::bail; 3use failure::bail;
7 4
5use tools::{Result, run_rustfmt, run, project_root};
6
8fn main() -> tools::Result<()> { 7fn main() -> tools::Result<()> {
9 run_rustfmt(tools::Overwrite)?; 8 run_rustfmt(tools::Overwrite)?;
10 update_staged() 9 update_staged()
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index d404db214..311bcb4d8 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -1,7 +1,8 @@
1use std::{ 1use std::{
2 fs,
3 collections::HashMap,
2 path::{Path, PathBuf}, 4 path::{Path, PathBuf},
3 process::{Command, Stdio}, 5 process::{Command, Stdio},
4 fs::copy,
5 io::{Error, ErrorKind} 6 io::{Error, ErrorKind}
6}; 7};
7 8
@@ -13,6 +14,10 @@ pub use teraron::{Mode, Overwrite, Verify};
13pub type Result<T> = std::result::Result<T, failure::Error>; 14pub type Result<T> = std::result::Result<T, failure::Error>;
14 15
15pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron"; 16pub const GRAMMAR: &str = "crates/ra_syntax/src/grammar.ron";
17const GRAMMAR_DIR: &str = "crates/ra_syntax/src/grammar";
18const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/ok";
19const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/err";
20
16pub const SYNTAX_KINDS: &str = "crates/ra_syntax/src/syntax_kinds/generated.rs.tera"; 21pub const SYNTAX_KINDS: &str = "crates/ra_syntax/src/syntax_kinds/generated.rs.tera";
17pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs.tera"; 22pub const AST: &str = "crates/ra_syntax/src/ast/generated.rs.tera";
18const TOOLCHAIN: &str = "stable"; 23const TOOLCHAIN: &str = "stable";
@@ -130,9 +135,9 @@ pub fn install_format_hook() -> Result<()> {
130 if !result_path.exists() { 135 if !result_path.exists() {
131 run("cargo build --package tools --bin pre-commit", ".")?; 136 run("cargo build --package tools --bin pre-commit", ".")?;
132 if cfg!(windows) { 137 if cfg!(windows) {
133 copy("./target/debug/pre-commit.exe", result_path)?; 138 fs::copy("./target/debug/pre-commit.exe", result_path)?;
134 } else { 139 } else {
135 copy("./target/debug/pre-commit", result_path)?; 140 fs::copy("./target/debug/pre-commit", result_path)?;
136 } 141 }
137 } else { 142 } else {
138 return Err(Error::new(ErrorKind::AlreadyExists, "Git hook already created").into()); 143 return Err(Error::new(ErrorKind::AlreadyExists, "Git hook already created").into());
@@ -156,3 +161,98 @@ pub fn run_fuzzer() -> Result<()> {
156 "./crates/ra_syntax", 161 "./crates/ra_syntax",
157 ) 162 )
158} 163}
164
165pub fn gen_tests(mode: Mode) -> Result<()> {
166 let tests = tests_from_dir(&project_root().join(Path::new(GRAMMAR_DIR)))?;
167 fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
168 let tests_dir = project_root().join(into);
169 if !tests_dir.is_dir() {
170 fs::create_dir_all(&tests_dir)?;
171 }
172 // ok is never actually read, but it needs to be specified to create a Test in existing_tests
173 let existing = existing_tests(&tests_dir, true)?;
174 for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
175 panic!("Test is deleted: {}", t);
176 }
177
178 let mut new_idx = existing.len() + 1;
179 for (name, test) in tests {
180 let path = match existing.get(name) {
181 Some((path, _test)) => path.clone(),
182 None => {
183 let file_name = format!("{:04}_{}.rs", new_idx, name);
184 new_idx += 1;
185 tests_dir.join(file_name)
186 }
187 };
188 teraron::update(&path, &test.text, mode)?;
189 }
190 Ok(())
191 }
192 install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
193 install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
194}
195
196#[derive(Default, Debug)]
197struct Tests {
198 pub ok: HashMap<String, Test>,
199 pub err: HashMap<String, Test>,
200}
201
202fn tests_from_dir(dir: &Path) -> Result<Tests> {
203 let mut res = Tests::default();
204 for entry in ::walkdir::WalkDir::new(dir) {
205 let entry = entry.unwrap();
206 if !entry.file_type().is_file() {
207 continue;
208 }
209 if entry.path().extension().unwrap_or_default() != "rs" {
210 continue;
211 }
212 process_file(&mut res, entry.path())?;
213 }
214 let grammar_rs = dir.parent().unwrap().join("grammar.rs");
215 process_file(&mut res, &grammar_rs)?;
216 return Ok(res);
217 fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
218 let text = fs::read_to_string(path)?;
219
220 for (_, test) in collect_tests(&text) {
221 if test.ok {
222 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
223 bail!("Duplicate test: {}", old_test.name)
224 }
225 } else {
226 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
227 bail!("Duplicate test: {}", old_test.name)
228 }
229 }
230 }
231 Ok(())
232 }
233}
234
235fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
236 let mut res = HashMap::new();
237 for file in fs::read_dir(dir)? {
238 let file = file?;
239 let path = file.path();
240 if path.extension().unwrap_or_default() != "rs" {
241 continue;
242 }
243 let name = {
244 let file_name = path.file_name().unwrap().to_str().unwrap();
245 file_name[5..file_name.len() - 3].to_string()
246 };
247 let text = fs::read_to_string(&path)?;
248 let test = Test {
249 name: name.clone(),
250 text,
251 ok,
252 };
253 if let Some(old) = res.insert(name, (path, test)) {
254 println!("Duplicate test: {:?}", old);
255 }
256 }
257 Ok(res)
258}
diff --git a/crates/tools/src/main.rs b/crates/tools/src/main.rs
index d6eabce6c..c3e293911 100644
--- a/crates/tools/src/main.rs
+++ b/crates/tools/src/main.rs
@@ -1,30 +1,13 @@
1use std::{ 1use clap::{App, SubCommand};
2 collections::HashMap,
3 fs,
4 path::{Path, PathBuf},
5};
6
7use clap::{App, Arg, SubCommand};
8use failure::bail;
9 2
10use tools::{ 3use tools::{
11 collect_tests, generate,install_format_hook, run, run_rustfmt, 4 generate, gen_tests, install_format_hook, run, run_rustfmt,
12 Mode, Overwrite, Result, Test, Verify, project_root, run_fuzzer 5 Overwrite, Result, run_fuzzer,
13}; 6};
14 7
15const GRAMMAR_DIR: &str = "crates/ra_syntax/src/grammar";
16const OK_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/ok";
17const ERR_INLINE_TESTS_DIR: &str = "crates/ra_syntax/tests/data/parser/inline/err";
18
19fn main() -> Result<()> { 8fn main() -> Result<()> {
20 let matches = App::new("tasks") 9 let matches = App::new("tasks")
21 .setting(clap::AppSettings::SubcommandRequiredElseHelp) 10 .setting(clap::AppSettings::SubcommandRequiredElseHelp)
22 .arg(
23 Arg::with_name("verify")
24 .long("--verify")
25 .help("Verify that generated code is up-to-date")
26 .global(true),
27 )
28 .subcommand(SubCommand::with_name("gen-syntax")) 11 .subcommand(SubCommand::with_name("gen-syntax"))
29 .subcommand(SubCommand::with_name("gen-tests")) 12 .subcommand(SubCommand::with_name("gen-tests"))
30 .subcommand(SubCommand::with_name("install-code")) 13 .subcommand(SubCommand::with_name("install-code"))
@@ -32,19 +15,14 @@ fn main() -> Result<()> {
32 .subcommand(SubCommand::with_name("format-hook")) 15 .subcommand(SubCommand::with_name("format-hook"))
33 .subcommand(SubCommand::with_name("fuzz-tests")) 16 .subcommand(SubCommand::with_name("fuzz-tests"))
34 .get_matches(); 17 .get_matches();
35 let mode = if matches.is_present("verify") {
36 Verify
37 } else {
38 Overwrite
39 };
40 match matches 18 match matches
41 .subcommand_name() 19 .subcommand_name()
42 .expect("Subcommand must be specified") 20 .expect("Subcommand must be specified")
43 { 21 {
44 "install-code" => install_code_extension()?, 22 "install-code" => install_code_extension()?,
45 "gen-tests" => gen_tests(mode)?, 23 "gen-tests" => gen_tests(Overwrite)?,
46 "gen-syntax" => generate(Overwrite)?, 24 "gen-syntax" => generate(Overwrite)?,
47 "format" => run_rustfmt(mode)?, 25 "format" => run_rustfmt(Overwrite)?,
48 "format-hook" => install_format_hook()?, 26 "format-hook" => install_format_hook()?,
49 "fuzz-tests" => run_fuzzer()?, 27 "fuzz-tests" => run_fuzzer()?,
50 _ => unreachable!(), 28 _ => unreachable!(),
@@ -52,101 +30,6 @@ fn main() -> Result<()> {
52 Ok(()) 30 Ok(())
53} 31}
54 32
55fn gen_tests(mode: Mode) -> Result<()> {
56 let tests = tests_from_dir(Path::new(GRAMMAR_DIR))?;
57 fn install_tests(tests: &HashMap<String, Test>, into: &str, mode: Mode) -> Result<()> {
58 let tests_dir = project_root().join(into);
59 if !tests_dir.is_dir() {
60 fs::create_dir_all(&tests_dir)?;
61 }
62 // ok is never actually read, but it needs to be specified to create a Test in existing_tests
63 let existing = existing_tests(&tests_dir, true)?;
64 for t in existing.keys().filter(|&t| !tests.contains_key(t)) {
65 panic!("Test is deleted: {}", t);
66 }
67
68 let mut new_idx = existing.len() + 1;
69 for (name, test) in tests {
70 let path = match existing.get(name) {
71 Some((path, _test)) => path.clone(),
72 None => {
73 let file_name = format!("{:04}_{}.rs", new_idx, name);
74 new_idx += 1;
75 tests_dir.join(file_name)
76 }
77 };
78 teraron::update(&path, &test.text, mode)?;
79 }
80 Ok(())
81 }
82 install_tests(&tests.ok, OK_INLINE_TESTS_DIR, mode)?;
83 install_tests(&tests.err, ERR_INLINE_TESTS_DIR, mode)
84}
85
86#[derive(Default, Debug)]
87struct Tests {
88 pub ok: HashMap<String, Test>,
89 pub err: HashMap<String, Test>,
90}
91
92fn tests_from_dir(dir: &Path) -> Result<Tests> {
93 let mut res = Tests::default();
94 for entry in ::walkdir::WalkDir::new(dir) {
95 let entry = entry.unwrap();
96 if !entry.file_type().is_file() {
97 continue;
98 }
99 if entry.path().extension().unwrap_or_default() != "rs" {
100 continue;
101 }
102 process_file(&mut res, entry.path())?;
103 }
104 let grammar_rs = dir.parent().unwrap().join("grammar.rs");
105 process_file(&mut res, &grammar_rs)?;
106 return Ok(res);
107 fn process_file(res: &mut Tests, path: &Path) -> Result<()> {
108 let text = fs::read_to_string(path)?;
109
110 for (_, test) in collect_tests(&text) {
111 if test.ok {
112 if let Some(old_test) = res.ok.insert(test.name.clone(), test) {
113 bail!("Duplicate test: {}", old_test.name)
114 }
115 } else {
116 if let Some(old_test) = res.err.insert(test.name.clone(), test) {
117 bail!("Duplicate test: {}", old_test.name)
118 }
119 }
120 }
121 Ok(())
122 }
123}
124
125fn existing_tests(dir: &Path, ok: bool) -> Result<HashMap<String, (PathBuf, Test)>> {
126 let mut res = HashMap::new();
127 for file in fs::read_dir(dir)? {
128 let file = file?;
129 let path = file.path();
130 if path.extension().unwrap_or_default() != "rs" {
131 continue;
132 }
133 let name = {
134 let file_name = path.file_name().unwrap().to_str().unwrap();
135 file_name[5..file_name.len() - 3].to_string()
136 };
137 let text = fs::read_to_string(&path)?;
138 let test = Test {
139 name: name.clone(),
140 text,
141 ok,
142 };
143 if let Some(old) = res.insert(name, (path, test)) {
144 println!("Duplicate test: {:?}", old);
145 }
146 }
147 Ok(res)
148}
149
150fn install_code_extension() -> Result<()> { 33fn install_code_extension() -> Result<()> {
151 run("cargo install --path crates/ra_lsp_server --force", ".")?; 34 run("cargo install --path crates/ra_lsp_server --force", ".")?;
152 if cfg!(windows) { 35 if cfg!(windows) {
diff --git a/crates/tools/tests/cli.rs b/crates/tools/tests/cli.rs
index 2d238d9ea..2ee4b5223 100644
--- a/crates/tools/tests/cli.rs
+++ b/crates/tools/tests/cli.rs
@@ -1,15 +1,23 @@
1extern crate tools; 1use tools::{generate, gen_tests, run_rustfmt, Verify};
2
3use tools::{generate, run_rustfmt, Verify};
4 2
5#[test] 3#[test]
6fn verify_template_generation() { 4fn generated_grammar_is_fresh() {
7 if let Err(error) = generate(Verify) { 5 if let Err(error) = generate(Verify) {
8 panic!("{}. Please update it by running `cargo gen-syntax`", error); 6 panic!("{}. Please update it by running `cargo gen-syntax`", error);
9 } 7 }
10} 8}
11 9
12#[test] 10#[test]
11fn generated_tests_are_fresh() {
12 if let Err(error) = gen_tests(Verify) {
13 panic!(
14 "{}. Please update tests by running `cargo gen-tests`",
15 error
16 );
17 }
18}
19
20#[test]
13fn check_code_formatting() { 21fn check_code_formatting() {
14 if let Err(error) = run_rustfmt(Verify) { 22 if let Err(error) = run_rustfmt(Verify) {
15 panic!( 23 panic!(