Repository: rust-analyzer/rust-analyzer
Pull request #3471 (2020-03-05 10:25:30)

Remove pwd


bors r+
🤖


Patch:
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index 9f59d590ce..e1cb12cca0 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -45,7 +45,8 @@ pub use crate::{
         StructField, Trait, Type, TypeAlias, TypeParam, Union, VariantDef,
     },
     has_source::HasSource,
-    semantics::{original_range, PathResolution, Semantics, SemanticsScope},
+    semantics::{original_range, Semantics, SemanticsScope},
+    source_analyzer::PathResolution,
 };
 
 pub use hir_def::{
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
index 965d185a47..7ce7857913 100644
--- a/crates/ra_hir/src/semantics.rs
+++ b/crates/ra_hir/src/semantics.rs
@@ -20,23 +20,10 @@ use crate::{
     db::HirDatabase,
     semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
     source_analyzer::{resolve_hir_path, SourceAnalyzer},
-    AssocItem, Function, HirFileId, ImplDef, InFile, Local, MacroDef, Module, ModuleDef, Name,
-    Origin, Path, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef,
+    Function, HirFileId, InFile, Local, MacroDef, Module, ModuleDef, Name, Origin, Path,
+    PathResolution, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef,
 };
 
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum PathResolution {
-    /// An item
-    Def(ModuleDef),
-    /// A local binding (only value namespace)
-    Local(Local),
-    /// A generic parameter
-    TypeParam(TypeParam),
-    SelfType(ImplDef),
-    Macro(MacroDef),
-    AssocItem(AssocItem),
-}
-
 /// Primary API to get semantic information, like types, from syntax trees.
 pub struct Semantics<'db, DB> {
     pub db: &'db DB,
diff --git a/crates/ra_hir/src/source_analyzer.rs b/crates/ra_hir/src/source_analyzer.rs
index f3f1ed05a3..33c566025e 100644
--- a/crates/ra_hir/src/source_analyzer.rs
+++ b/crates/ra_hir/src/source_analyzer.rs
@@ -20,12 +20,12 @@ use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
 use hir_ty::{InEnvironment, InferenceResult, TraitEnvironment};
 use ra_syntax::{
     ast::{self, AstNode},
-    SyntaxNode, SyntaxNodePtr, TextUnit,
+    SyntaxNode, SyntaxNodePtr, TextRange, TextUnit,
 };
 
 use crate::{
-    db::HirDatabase, semantics::PathResolution, Adt, Const, EnumVariant, Function, Local, MacroDef,
-    ModPath, ModuleDef, Path, PathKind, Static, Struct, Trait, Type, TypeAlias, TypeParam,
+    db::HirDatabase, Adt, Const, EnumVariant, Function, Local, MacroDef, ModPath, ModuleDef, Path,
+    PathKind, Static, Struct, Trait, Type, TypeAlias, TypeParam,
 };
 
 /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
@@ -40,6 +40,25 @@ pub(crate) struct SourceAnalyzer {
     scopes: Option<Arc<ExprScopes>>,
 }
 
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PathResolution {
+    /// An item
+    Def(crate::ModuleDef),
+    /// A local binding (only value namespace)
+    Local(Local),
+    /// A generic parameter
+    TypeParam(TypeParam),
+    SelfType(crate::ImplDef),
+    Macro(MacroDef),
+    AssocItem(crate::AssocItem),
+}
+
+#[derive(Debug)]
+pub struct ReferenceDescriptor {
+    pub range: TextRange,
+    pub name: String,
+}
+
 impl SourceAnalyzer {
     pub(crate) fn new_for_body(
         db: &impl HirDatabase,
diff --git a/crates/ra_hir_expand/src/builtin_derive.rs b/crates/ra_hir_expand/src/builtin_derive.rs
index a5b50a832b..87224481ce 100644
--- a/crates/ra_hir_expand/src/builtin_derive.rs
+++ b/crates/ra_hir_expand/src/builtin_derive.rs
@@ -266,7 +266,7 @@ mod tests {
             BuiltinDeriveExpander::Copy,
         );
 
-        assert_eq!(expanded, "impl< >std::marker::CopyforFoo< >{}");
+        assert_eq!(expanded, "impl <>std::marker::CopyforFoo <>{}");
     }
 
     #[test]
diff --git a/crates/ra_hir_expand/src/builtin_macro.rs b/crates/ra_hir_expand/src/builtin_macro.rs
index b2c8a911f0..1f380b5716 100644
--- a/crates/ra_hir_expand/src/builtin_macro.rs
+++ b/crates/ra_hir_expand/src/builtin_macro.rs
@@ -367,7 +367,7 @@ mod tests {
             "#,
         );
 
-        assert_eq!(expanded, "std::option::Option::None:: < &str>");
+        assert_eq!(expanded, "std::option::Option::None:: <&str>");
     }
 
     #[test]
@@ -414,7 +414,7 @@ mod tests {
 
         assert_eq!(
             expanded,
-            r#"std::fmt::Arguments::new_v1(&[], &[std::fmt::ArgumentV1::new(&(arg1(a,b,c)),std::fmt::Display::fmt),std::fmt::ArgumentV1::new(&(arg2),std::fmt::Display::fmt),])"#
+            r#"std::fmt::Arguments::new_v1(&[] ,&[std::fmt::ArgumentV1::new(&(arg1(a,b,c)),std::fmt::Display::fmt),std::fmt::ArgumentV1::new(&(arg2),std::fmt::Display::fmt),])"#
         );
     }
 }
diff --git a/crates/ra_hir_expand/src/db.rs b/crates/ra_hir_expand/src/db.rs
index f3a84cacc3..32e0d5ced3 100644
--- a/crates/ra_hir_expand/src/db.rs
+++ b/crates/ra_hir_expand/src/db.rs
@@ -176,20 +176,10 @@ pub(crate) fn parse_macro(
                 MacroCallId::LazyMacro(id) => {
                     let loc: MacroCallLoc = db.lookup_intern_macro(id);
                     let node = loc.kind.node(db);
-
-                    // collect parent information for warning log
-                    let parents = std::iter::successors(loc.kind.file_id().call_node(db), |it| {
-                        it.file_id.call_node(db)
-                    })
-                    .map(|n| format!("{:#}", n.value))
-                    .collect::<Vec<_>>()
-                    .join("\n");
-
                     log::warn!(
-                        "fail on macro_parse: (reason: {} macro_call: {:#}) parents: {}",
+                        "fail on macro_parse: (reason: {} macro_call: {:#})",
                         err,
-                        node.value,
-                        parents
+                        node.value
                     );
                 }
                 _ => {
diff --git a/crates/ra_mbe/src/mbe_expander/matcher.rs b/crates/ra_mbe/src/mbe_expander/matcher.rs
index ffba03898a..2bdea11e14 100644
--- a/crates/ra_mbe/src/mbe_expander/matcher.rs
+++ b/crates/ra_mbe/src/mbe_expander/matcher.rs
@@ -155,60 +155,6 @@ impl<'a> TtIter<'a> {
         ok
     }
 
-    pub(crate) fn expect_tt(&mut self) -> Result<tt::TokenTree, ()> {
-        let tt = self.next().ok_or_else(|| ())?.clone();
-        let punct = match tt {
-            tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.spacing == tt::Spacing::Joint => {
-                punct
-            }
-            _ => return Ok(tt),
-        };
-
-        let (second, third) = match (self.peek_n(0), self.peek_n(1)) {
-            (
-                Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p2))),
-                Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p3))),
-            ) if p2.spacing == tt::Spacing::Joint => (p2.char, Some(p3.char)),
-            (Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p2))), _) => (p2.char, None),
-            _ => return Ok(tt),
-        };
-
-        match (punct.char, second, third) {
-            ('.', '.', Some('.'))
-            | ('.', '.', Some('='))
-            | ('<', '<', Some('='))
-            | ('>', '>', Some('=')) => {
-                let tt2 = self.next().unwrap().clone();
-                let tt3 = self.next().unwrap().clone();
-                Ok(tt::Subtree { delimiter: None, token_trees: vec![tt, tt2, tt3] }.into())
-            }
-            ('-', '=', None)
-            | ('-', '>', None)
-            | (':', ':', None)
-            | ('!', '=', None)
-            | ('.', '.', None)
-            | ('*', '=', None)
-            | ('/', '=', None)
-            | ('&', '&', None)
-            | ('&', '=', None)
-            | ('%', '=', None)
-            | ('^', '=', None)
-            | ('+', '=', None)
-            | ('<', '<', None)
-            | ('<', '=', None)
-            | ('=', '=', None)
-            | ('=', '>', None)
-            | ('>', '=', None)
-            | ('>', '>', None)
-            | ('|', '=', None)
-            | ('|', '|', None) => {
-                let tt2 = self.next().unwrap().clone();
-                Ok(tt::Subtree { delimiter: None, token_trees: vec![tt.clone(), tt2] }.into())
-            }
-            _ => Ok(tt),
-        }
-    }
-
     pub(crate) fn expect_lifetime(&mut self) -> Result<&tt::Ident, ()> {
         let ident = self.expect_ident()?;
         // check if it start from "`"
@@ -356,7 +302,7 @@ fn match_meta_var(kind: &str, input: &mut TtIter) -> Result<Option<Fragment>, Ex
                     let ident = input.expect_ident().map_err(|()| err!("expected ident"))?.clone();
                     tt::Leaf::from(ident).into()
                 }
-                "tt" => input.expect_tt().map_err(|()| err!())?.clone(),
+                "tt" => input.next().ok_or_else(|| err!())?.clone(),
                 "lifetime" => {
                     let ident = input.expect_lifetime().map_err(|()| err!())?;
                     tt::Leaf::Ident(ident.clone()).into()
diff --git a/crates/ra_mbe/src/syntax_bridge.rs b/crates/ra_mbe/src/syntax_bridge.rs
index d8ee74faaa..2aaf0215fa 100644
--- a/crates/ra_mbe/src/syntax_bridge.rs
+++ b/crates/ra_mbe/src/syntax_bridge.rs
@@ -388,12 +388,11 @@ impl<'a> TreeSink for TtTreeSink<'a> {
             return;
         }
 
-        let mut last = self.cursor;
         for _ in 0..n_tokens {
             if self.cursor.eof() {
                 break;
             }
-            last = self.cursor;
+
             let text: SmolStr = match self.cursor.token_tree() {
                 Some(tt::TokenTree::Leaf(leaf)) => {
                     // Mark the range if needed
@@ -442,11 +441,11 @@ impl<'a> TreeSink for TtTreeSink<'a> {
         self.inner.token(kind, text);
 
         // Add whitespace between adjoint puncts
-        let next = last.bump();
+        let next = self.cursor.bump();
         if let (
             Some(tt::TokenTree::Leaf(tt::Leaf::Punct(curr))),
             Some(tt::TokenTree::Leaf(tt::Leaf::Punct(_))),
-        ) = (last.token_tree(), next.token_tree())
+        ) = (self.cursor.token_tree(), next.token_tree())
         {
             if curr.spacing == tt::Spacing::Alone {
                 self.inner.token(WHITESPACE, " ".into());
diff --git a/crates/ra_mbe/src/tt_iter.rs b/crates/ra_mbe/src/tt_iter.rs
index 100184e66a..319f1ee65f 100644
--- a/crates/ra_mbe/src/tt_iter.rs
+++ b/crates/ra_mbe/src/tt_iter.rs
@@ -53,10 +53,6 @@ impl<'a> TtIter<'a> {
             _ => Err(()),
         }
     }
-
-    pub(crate) fn peek_n(&self, n: usize) -> Option<&tt::TokenTree> {
-        self.inner.as_slice().get(n)
-    }
 }
 
 impl<'a> Iterator for TtIter<'a> {
diff --git a/xtask/src/dist.rs b/xtask/src/dist.rs
index 737751ae89..821ba041bb 100644
--- a/xtask/src/dist.rs
+++ b/xtask/src/dist.rs
@@ -3,7 +3,7 @@ use std::path::PathBuf;
 use anyhow::Result;
 
 use crate::{
-    not_bash::{fs2, pushd, pwd, rm_rf, run},
+    not_bash::{fs2, pushd, rm_rf, run},
     project_root,
 };
 
@@ -22,7 +22,7 @@ pub fn run_dist(nightly: bool) -> Result<()> {
 fn dist_client(nightly: bool) -> Result<()> {
     let _d = pushd("./editors/code");
 
-    let package_json_path = pwd().join("package.json");
+    let package_json_path = PathBuf::from("./package.json");
     let original_package_json = fs2::read_to_string(&package_json_path)?;
     let _restore =
         Restore { path: package_json_path.clone(), contents: original_package_json.clone() };
@@ -39,6 +39,7 @@ fn dist_client(nightly: bool) -> Result<()> {
     }
     fs2::write(package_json_path, package_json)?;
 
+    run!("npm ci")?;
     run!("npx vsce package -o ../../dist/rust-analyzer.vsix")?;
     Ok(())
 }
diff --git a/xtask/src/not_bash.rs b/xtask/src/not_bash.rs
index 1697b7fcd1..2d45e5dff4 100644
--- a/xtask/src/not_bash.rs
+++ b/xtask/src/not_bash.rs
@@ -71,10 +71,6 @@ pub fn pushd(path: impl Into<PathBuf>) -> Pushd {
     Pushd { _p: () }
 }
 
-pub fn pwd() -> PathBuf {
-    Env::with(|env| env.cwd())
-}
-
 impl Drop for Pushd {
     fn drop(&mut self) {
         Env::with(|env| env.popd())
@@ -101,6 +97,7 @@ pub fn run_process(cmd: String, echo: bool) -> Result<String> {
 fn run_process_inner(cmd: &str, echo: bool) -> Result<String> {
     let mut args = shelx(cmd);
     let binary = args.remove(0);
+    let current_dir = Env::with(|it| it.cwd().to_path_buf());
 
     if echo {
         println!("> {}", cmd)
@@ -108,7 +105,7 @@ fn run_process_inner(cmd: &str, echo: bool) -> Result<String> {
 
     let output = Command::new(binary)
         .args(args)
-        .current_dir(pwd())
+        .current_dir(current_dir)
         .stdin(Stdio::null())
         .stderr(Stdio::inherit())
         .output()?;
@@ -130,7 +127,6 @@ fn shelx(cmd: &str) -> Vec<String> {
     cmd.split_whitespace().map(|it| it.to_string()).collect()
 }
 
-#[derive(Default)]
 struct Env {
     pushd_stack: Vec<PathBuf>,
 }
@@ -138,19 +134,23 @@ struct Env {
 impl Env {
     fn with<F: FnOnce(&mut Env) -> T, T>(f: F) -> T {
         thread_local! {
-            static ENV: RefCell<Env> = Default::default();
+            static ENV: RefCell<Env> = RefCell::new(Env {
+                pushd_stack: vec![env::current_dir().unwrap()]
+            });
         }
         ENV.with(|it| f(&mut *it.borrow_mut()))
     }
 
     fn pushd(&mut self, dir: PathBuf) {
         let dir = self.cwd().join(dir);
-        self.pushd_stack.push(dir)
+        self.pushd_stack.push(dir);
+        env::set_current_dir(self.cwd()).unwrap();
     }
     fn popd(&mut self) {
         self.pushd_stack.pop().unwrap();
+        env::set_current_dir(self.cwd()).unwrap();
     }
-    fn cwd(&self) -> PathBuf {
-        self.pushd_stack.last().cloned().unwrap_or_else(|| env::current_dir().unwrap())
+    fn cwd(&self) -> &Path {
+        self.pushd_stack.last().unwrap()
     }
 }


Test patch:
diff --git a/crates/ra_mbe/src/tests.rs b/crates/ra_mbe/src/tests.rs
index 304867881d..1dba829154 100644
--- a/crates/ra_mbe/src/tests.rs
+++ b/crates/ra_mbe/src/tests.rs
@@ -825,50 +825,6 @@ fn test_tt_group() {
     )
     .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
 }
-
-#[test]
-fn test_tt_composite() {
-    parse_macro(
-        r#"
-            macro_rules! foo {
-                 ($i:tt) => { 0 }
-            }
-    "#,
-    )
-    .assert_expand_items(r#"foo! { => }"#, r#"0"#);
-}
-
-#[test]
-fn test_tt_composite2() {
-    let node = parse_macro(
-        r#"
-            macro_rules! foo {
-                ($($tt:tt)*) => { abs!(=> $($tt)*) }
-            }
-    "#,
-    )
-    .expand_items(r#"foo!{#}"#);
-
-    let res = format!("{:#?}", &node);
-    assert_eq_text!(
-        res.trim(),
-        r###"MACRO_ITEMS@[0; 10)
-  MACRO_CALL@[0; 10)
-    PATH@[0; 3)
-      PATH_SEGMENT@[0; 3)
-        NAME_REF@[0; 3)
-          IDENT@[0; 3) "abs"
-    EXCL@[3; 4) "!"
-    TOKEN_TREE@[4; 10)
-      L_PAREN@[4; 5) "("
-      EQ@[5; 6) "="
-      R_ANGLE@[6; 7) ">"
-      WHITESPACE@[7; 8) " "
-      POUND@[8; 9) "#"
-      R_PAREN@[9; 10) ")""###
-    );
-}
-
 #[test]
 fn test_lifetime() {
     parse_macro(