Repository: rust-analyzer/rust-analyzer
Pull request #4142 (2020-04-25 17:53:10)

Remove unnecessary async from vscode language client creation


Patch:
diff --git a/crates/ra_hir_def/src/attr.rs b/crates/ra_hir_def/src/attr.rs
index 5a86af8ba3..714a66b027 100644
--- a/crates/ra_hir_def/src/attr.rs
+++ b/crates/ra_hir_def/src/attr.rs
@@ -13,8 +13,7 @@ use ra_syntax::{
 use tt::Subtree;
 
 use crate::{
-    db::DefDatabase, nameres::ModuleSource, path::ModPath, src::HasChildSource, src::HasSource,
-    AdtId, AttrDefId, Lookup,
+    db::DefDatabase, path::ModPath, src::HasChildSource, src::HasSource, AdtId, AttrDefId, Lookup,
 };
 
 #[derive(Default, Debug, Clone, PartialEq, Eq)]
@@ -38,19 +37,11 @@ impl Attrs {
         match def {
             AttrDefId::ModuleId(module) => {
                 let def_map = db.crate_def_map(module.krate);
-                let mod_data = &def_map[module.local_id];
-                match mod_data.declaration_source(db) {
-                    Some(it) => {
-                        Attrs::from_attrs_owner(db, it.as_ref().map(|it| it as &dyn AttrsOwner))
-                    }
-                    None => Attrs::from_attrs_owner(
-                        db,
-                        mod_data.definition_source(db).as_ref().map(|src| match src {
-                            ModuleSource::SourceFile(file) => file as &dyn AttrsOwner,
-                            ModuleSource::Module(module) => module as &dyn AttrsOwner,
-                        }),
-                    ),
-                }
+                let src = match def_map[module.local_id].declaration_source(db) {
+                    Some(it) => it,
+                    None => return Attrs::default(),
+                };
+                Attrs::from_attrs_owner(db, src.as_ref().map(|it| it as &dyn AttrsOwner))
             }
             AttrDefId::FieldId(it) => {
                 let src = it.parent.child_source(db);
@@ -115,9 +106,7 @@ pub struct Attr {
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum AttrInput {
-    /// `#[attr = "string"]`
     Literal(SmolStr),
-    /// `#[attr(subtree)]`
     TokenTree(Subtree),
 }
 
diff --git a/crates/ra_hir_def/src/find_path.rs b/crates/ra_hir_def/src/find_path.rs
index 70dcb03e6e..81eff5bfef 100644
--- a/crates/ra_hir_def/src/find_path.rs
+++ b/crates/ra_hir_def/src/find_path.rs
@@ -19,7 +19,7 @@ impl ModPath {
 
     // When std library is present, paths starting with `std::`
     // should be preferred over paths starting with `core::` and `alloc::`
-    fn can_start_with_std(&self) -> bool {
+    fn should_start_with_std(&self) -> bool {
         self.segments
             .first()
             .filter(|&first_segment| {
@@ -132,9 +132,6 @@ fn find_path_inner(
     }
 
     // - otherwise, look for modules containing (reexporting) it and import it from one of those
-    let crate_root = ModuleId { local_id: def_map.root, krate: from.krate };
-    let crate_attrs = db.attrs(crate_root.into());
-    let prefer_no_std = crate_attrs.by_key("no_std").exists();
     let importable_locations = find_importable_locations(db, item, from);
     let mut best_path = None;
     let mut best_path_len = max_len;
@@ -150,32 +147,21 @@ fn find_path_inner(
         };
         path.segments.push(name);
 
-        let new_path = if let Some(best_path) = best_path {
-            select_best_path(best_path, path, prefer_no_std)
-        } else {
-            path
-        };
+        let new_path =
+            if let Some(best_path) = best_path { select_best_path(best_path, path) } else { path };
         best_path_len = new_path.len();
         best_path = Some(new_path);
     }
     best_path
 }
 
-fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
-    if old_path.starts_with_std() && new_path.can_start_with_std() {
+fn select_best_path(old_path: ModPath, new_path: ModPath) -> ModPath {
+    if old_path.starts_with_std() && new_path.should_start_with_std() {
         tested_by!(prefer_std_paths);
-        if prefer_no_std {
-            new_path
-        } else {
-            old_path
-        }
-    } else if new_path.starts_with_std() && old_path.can_start_with_std() {
+        old_path
+    } else if new_path.starts_with_std() && old_path.should_start_with_std() {
         tested_by!(prefer_std_paths);
-        if prefer_no_std {
-            old_path
-        } else {
-            new_path
-        }
+        new_path
     } else if new_path.len() < old_path.len() {
         new_path
     } else {
@@ -526,54 +512,6 @@ mod tests {
         check_found_path(code, "std::sync::Arc");
     }
 
-    #[test]
-    fn prefer_alloc_paths_over_std() {
-        covers!(prefer_std_paths);
-        let code = r#"
-        //- /main.rs crate:main deps:alloc,std
-        #![no_std]
-
-        <|>
-
-        //- /std.rs crate:std deps:alloc
-
-        pub mod sync {
-            pub use alloc::sync::Arc;
-        }
-
-        //- /zzz.rs crate:alloc
-
-        pub mod sync {
-            pub struct Arc;
-        }
-        "#;
-        check_found_path(code, "alloc::sync::Arc");
-    }
-
-    #[test]
-    fn prefer_core_paths_over_std() {
-        covers!(prefer_std_paths);
-        let code = r#"
-        //- /main.rs crate:main deps:core,std
-        #![no_std]
-
-        <|>
-
-        //- /std.rs crate:std deps:core
-
-        pub mod fmt {
-            pub use core::fmt::Error;
-        }
-
-        //- /zzz.rs crate:core
-
-        pub mod fmt {
-            pub struct Error;
-        }
-        "#;
-        check_found_path(code, "core::fmt::Error");
-    }
-
     #[test]
     fn prefer_shorter_paths_if_not_alloc() {
         let code = r#"
diff --git a/crates/ra_mbe/src/lib.rs b/crates/ra_mbe/src/lib.rs
index 1a020398e9..535b7daa07 100644
--- a/crates/ra_mbe/src/lib.rs
+++ b/crates/ra_mbe/src/lib.rs
@@ -19,7 +19,6 @@ use crate::{
 #[derive(Debug, PartialEq, Eq)]
 pub enum ParseError {
     Expected(String),
-    RepetitionEmtpyTokenTree,
 }
 
 #[derive(Debug, PartialEq, Eq)]
@@ -195,46 +194,20 @@ impl Rule {
     }
 }
 
-fn to_parse_error(e: ExpandError) -> ParseError {
-    let msg = match e {
-        ExpandError::InvalidRepeat => "invalid repeat".to_string(),
-        _ => "invalid macro definition".to_string(),
-    };
-    ParseError::Expected(msg)
-}
-
 fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
     for op in parse_pattern(pattern) {
-        let op = op.map_err(to_parse_error)?;
-
+        let op = match op {
+            Ok(it) => it,
+            Err(e) => {
+                let msg = match e {
+                    ExpandError::InvalidRepeat => "invalid repeat".to_string(),
+                    _ => "invalid macro definition".to_string(),
+                };
+                return Err(ParseError::Expected(msg));
+            }
+        };
         match op {
-            Op::TokenTree(tt::TokenTree::Subtree(subtree)) => validate(subtree)?,
-            Op::Repeat { subtree, separator, .. } => {
-                // Checks that no repetition which could match an empty token
-                // https://github.com/rust-lang/rust/blob/a58b1ed44f5e06976de2bdc4d7dc81c36a96934f/src/librustc_expand/mbe/macro_rules.rs#L558
-
-                if separator.is_none() {
-                    if parse_pattern(subtree).all(|child_op| {
-                        match child_op.map_err(to_parse_error) {
-                            Ok(Op::Var { kind, .. }) => {
-                                // vis is optional
-                                if kind.map_or(false, |it| it == "vis") {
-                                    return true;
-                                }
-                            }
-                            Ok(Op::Repeat { kind, .. }) => {
-                                return matches!(
-                                    kind,
-                                    parser::RepeatKind::ZeroOrMore | parser::RepeatKind::ZeroOrOne
-                                )
-                            }
-                            _ => {}
-                        }
-                        false
-                    }) {
-                        return Err(ParseError::RepetitionEmtpyTokenTree);
-                    }
-                }
+            Op::TokenTree(tt::TokenTree::Subtree(subtree)) | Op::Repeat { subtree, .. } => {
                 validate(subtree)?
             }
             _ => (),
@@ -243,7 +216,6 @@ fn validate(pattern: &tt::Subtree) -> Result<(), ParseError> {
     Ok(())
 }
 
-#[derive(Debug)]
 pub struct ExpandResult<T>(pub T, pub Option<ExpandError>);
 
 impl<T> ExpandResult<T> {
diff --git a/editors/code/src/client.ts b/editors/code/src/client.ts
index 0ad4b63aeb..97e7940915 100644
--- a/editors/code/src/client.ts
+++ b/editors/code/src/client.ts
@@ -4,7 +4,7 @@ import * as vscode from 'vscode';
 import { CallHierarchyFeature } from 'vscode-languageclient/lib/callHierarchy.proposed';
 import { SemanticTokensFeature, DocumentSemanticsTokensSignature } from 'vscode-languageclient/lib/semanticTokens.proposed';
 
-export async function createClient(serverPath: string, cwd: string): Promise<lc.LanguageClient> {
+export function createClient(serverPath: string, cwd: string): lc.LanguageClient {
     // '.' Is the fallback if no folder is open
     // TODO?: Workspace folders support Uri's (eg: file://test.txt).
     // It might be a good idea to test if the uri points to a file.
diff --git a/editors/code/src/ctx.ts b/editors/code/src/ctx.ts
index f7ed62d035..41df119910 100644
--- a/editors/code/src/ctx.ts
+++ b/editors/code/src/ctx.ts
@@ -21,7 +21,7 @@ export class Ctx {
         serverPath: string,
         cwd: string,
     ): Promise<Ctx> {
-        const client = await createClient(serverPath, cwd);
+        const client = createClient(serverPath, cwd);
         const res = new Ctx(config, extCtx, client, serverPath);
         res.pushCleanup(client.start());
         await client.onReady();


Test patch:
diff --git a/crates/ra_mbe/src/tests.rs b/crates/ra_mbe/src/tests.rs
index 0d924ce582..7ceec7752a 100644
--- a/crates/ra_mbe/src/tests.rs
+++ b/crates/ra_mbe/src/tests.rs
@@ -1657,7 +1657,7 @@ impl MacroFixture {
     }
 }
 
-fn parse_macro_to_tt(ra_fixture: &str) -> tt::Subtree {
+pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
     let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
     let macro_definition =
         source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
@@ -1671,24 +1671,10 @@ fn parse_macro_to_tt(ra_fixture: &str) -> tt::Subtree {
     .0;
     assert_eq!(definition_tt, parsed);
 
-    definition_tt
-}
-
-pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
-    let definition_tt = parse_macro_to_tt(ra_fixture);
     let rules = MacroRules::parse(&definition_tt).unwrap();
     MacroFixture { rules }
 }
 
-pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
-    let definition_tt = parse_macro_to_tt(ra_fixture);
-
-    match MacroRules::parse(&definition_tt) {
-        Ok(_) => panic!("Expect error"),
-        Err(err) => err,
-    }
-}
-
 pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
     let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
     let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
@@ -1854,27 +1840,6 @@ fn test_no_space_after_semi_colon() {
     );
 }
 
-// https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
-#[test]
-fn test_rustc_issue_57597() {
-    fn test_error(fixture: &str) {
-        assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmtpyTokenTree);
-    }
-
-    test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
-    test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
-    test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
-    test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
-}
-
 #[test]
 fn test_expand_bad_literal() {
     parse_macro(