Repository: rust-analyzer/rust-analyzer
Pull request #2132 (2019-10-30 17:49:14)

echo cargo version during install


Patch:
diff --git a/Cargo.lock b/Cargo.lock
index fdacd82a70..66ff1285a0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1019,18 +1019,11 @@ name = "ra_hir_def"
 version = "0.1.0"
 dependencies = [
  "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
- "once_cell 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "ra_arena 0.1.0",
- "ra_cfg 0.1.0",
  "ra_db 0.1.0",
  "ra_hir_expand 0.1.0",
- "ra_mbe 0.1.0",
  "ra_prof 0.1.0",
  "ra_syntax 0.1.0",
- "ra_tt 0.1.0",
- "relative-path 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
- "test_utils 0.1.0",
 ]
 
 [[package]]
diff --git a/crates/ra_hir/src/adt.rs b/crates/ra_hir/src/adt.rs
index 97424b39e0..3e9cd3c63d 100644
--- a/crates/ra_hir/src/adt.rs
+++ b/crates/ra_hir/src/adt.rs
@@ -3,14 +3,13 @@
 
 use std::sync::Arc;
 
-use hir_def::type_ref::TypeRef;
-use hir_expand::name::AsName;
 use ra_arena::{impl_arena_id, Arena, RawId};
 use ra_syntax::ast::{self, NameOwner, StructKind, TypeAscriptionOwner};
 
 use crate::{
     db::{AstDatabase, DefDatabase, HirDatabase},
-    Enum, EnumVariant, FieldSource, HasSource, Module, Name, Source, Struct, StructField,
+    type_ref::TypeRef,
+    AsName, Enum, EnumVariant, FieldSource, HasSource, Module, Name, Source, Struct, StructField,
 };
 
 impl Struct {
diff --git a/crates/ra_hir_def/src/attr.rs b/crates/ra_hir/src/attr.rs
similarity index 68%
rename from crates/ra_hir_def/src/attr.rs
rename to crates/ra_hir/src/attr.rs
index 0e961ca12a..bd159a5665 100644
--- a/crates/ra_hir_def/src/attr.rs
+++ b/crates/ra_hir/src/attr.rs
@@ -2,7 +2,6 @@
 
 use std::sync::Arc;
 
-use hir_expand::hygiene::Hygiene;
 use mbe::ast_to_token_tree;
 use ra_cfg::CfgOptions;
 use ra_syntax::{
@@ -11,10 +10,10 @@ use ra_syntax::{
 };
 use tt::Subtree;
 
-use crate::path::Path;
+use crate::{db::AstDatabase, path::Path, HirFileId, Source};
 
 #[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Attr {
+pub(crate) struct Attr {
     pub(crate) path: Path,
     pub(crate) input: Option<AttrInput>,
 }
@@ -26,8 +25,11 @@ pub enum AttrInput {
 }
 
 impl Attr {
-    pub(crate) fn from_src(ast: ast::Attr, hygiene: &Hygiene) -> Option<Attr> {
-        let path = Path::from_src(ast.path()?, hygiene)?;
+    pub(crate) fn from_src(
+        Source { file_id, ast }: Source<ast::Attr>,
+        db: &impl AstDatabase,
+    ) -> Option<Attr> {
+        let path = Path::from_src(Source { file_id, ast: ast.path()? }, db)?;
         let input = match ast.input() {
             None => None,
             Some(ast::AttrInput::Literal(lit)) => {
@@ -43,22 +45,26 @@ impl Attr {
         Some(Attr { path, input })
     }
 
-    pub fn from_attrs_owner(owner: &dyn AttrsOwner, hygiene: &Hygiene) -> Option<Arc<[Attr]>> {
+    pub(crate) fn from_attrs_owner(
+        file_id: HirFileId,
+        owner: &dyn AttrsOwner,
+        db: &impl AstDatabase,
+    ) -> Option<Arc<[Attr]>> {
         let mut attrs = owner.attrs().peekable();
         if attrs.peek().is_none() {
             // Avoid heap allocation
             return None;
         }
-        Some(attrs.flat_map(|ast| Attr::from_src(ast, hygiene)).collect())
+        Some(attrs.flat_map(|ast| Attr::from_src(Source { file_id, ast }, db)).collect())
     }
 
-    pub fn is_simple_atom(&self, name: &str) -> bool {
+    pub(crate) fn is_simple_atom(&self, name: &str) -> bool {
         // FIXME: Avoid cloning
         self.path.as_ident().map_or(false, |s| s.to_string() == name)
     }
 
     // FIXME: handle cfg_attr :-)
-    pub fn as_cfg(&self) -> Option<&Subtree> {
+    pub(crate) fn as_cfg(&self) -> Option<&Subtree> {
         if !self.is_simple_atom("cfg") {
             return None;
         }
@@ -68,7 +74,7 @@ impl Attr {
         }
     }
 
-    pub fn as_path(&self) -> Option<&SmolStr> {
+    pub(crate) fn as_path(&self) -> Option<&SmolStr> {
         if !self.is_simple_atom("path") {
             return None;
         }
@@ -78,7 +84,7 @@ impl Attr {
         }
     }
 
-    pub fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> Option<bool> {
+    pub(crate) fn is_cfg_enabled(&self, cfg_options: &CfgOptions) -> Option<bool> {
         cfg_options.is_cfg_enabled(self.as_cfg()?)
     }
 }
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index a6ce23dd10..1a790b2f30 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -5,15 +5,8 @@ pub(crate) mod docs;
 
 use std::sync::Arc;
 
-use hir_def::{
-    type_ref::{Mutability, TypeRef},
-    CrateModuleId, ModuleId,
-};
-use hir_expand::name::{
-    self, AsName, BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16,
-    U32, U64, U8, USIZE,
-};
-use ra_db::{CrateId, Edition};
+use hir_def::{CrateModuleId, ModuleId};
+use ra_db::{CrateId, Edition, FileId};
 use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner};
 
 use crate::{
@@ -27,6 +20,10 @@ use crate::{
         TypeAliasId,
     },
     impl_block::ImplBlock,
+    name::{
+        BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16, U32, U64,
+        U8, USIZE,
+    },
     nameres::{ImportId, ModuleScope, Namespace},
     resolve::{Resolver, Scope, TypeNs},
     traits::TraitData,
@@ -34,7 +31,9 @@ use crate::{
         primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness},
         InferenceResult, TraitRef,
     },
-    Either, HasSource, Name, Ty,
+    type_ref::Mutability,
+    type_ref::TypeRef,
+    AsName, AstId, Either, HasSource, Name, Ty,
 };
 
 /// hir::Crate describes a single crate. It's the main interface with which
@@ -148,7 +147,31 @@ impl_froms!(
     BuiltinType
 );
 
-pub use hir_def::ModuleSource;
+pub enum ModuleSource {
+    SourceFile(ast::SourceFile),
+    Module(ast::Module),
+}
+
+impl ModuleSource {
+    pub(crate) fn new(
+        db: &(impl DefDatabase + AstDatabase),
+        file_id: Option<FileId>,
+        decl_id: Option<AstId<ast::Module>>,
+    ) -> ModuleSource {
+        match (file_id, decl_id) {
+            (Some(file_id), _) => {
+                let source_file = db.parse(file_id).tree();
+                ModuleSource::SourceFile(source_file)
+            }
+            (None, Some(item_id)) => {
+                let module = item_id.to_node(db);
+                assert!(module.item_list().is_some(), "expected inline module");
+                ModuleSource::Module(module)
+            }
+            (None, None) => panic!(),
+        }
+    }
+}
 
 impl Module {
     pub(crate) fn new(krate: Crate, crate_module_id: CrateModuleId) -> Module {
@@ -899,7 +922,9 @@ impl Trait {
             .where_predicates
             .iter()
             .filter_map(|pred| match &pred.type_ref {
-                TypeRef::Path(p) if p.as_ident() == Some(&name::SELF_TYPE) => pred.bound.as_path(),
+                TypeRef::Path(p) if p.as_ident() == Some(&crate::name::SELF_TYPE) => {
+                    pred.bound.as_path()
+                }
                 _ => None,
             })
             .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) {
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs
index ebfd970ebc..8f6cb2da7d 100644
--- a/crates/ra_hir/src/db.rs
+++ b/crates/ra_hir/src/db.rs
@@ -12,21 +12,18 @@ use crate::{
     ids,
     impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks},
     lang_item::{LangItemTarget, LangItems},
-    nameres::{CrateDefMap, Namespace},
+    nameres::{CrateDefMap, ImportSourceMap, Namespace, RawItems},
     traits::TraitData,
     ty::{
         method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate,
         InferenceResult, Substs, Ty, TypableDef, TypeCtor,
     },
     type_alias::TypeAliasData,
-    Const, ConstData, Crate, DefWithBody, Enum, ExprScopes, FnData, Function, Module, Static,
-    Struct, StructField, Trait, TypeAlias,
+    Const, ConstData, Crate, DefWithBody, Enum, ExprScopes, FnData, Function, HirFileId, Module,
+    Static, Struct, StructField, Trait, TypeAlias,
 };
 
-pub use hir_def::db::{
-    DefDatabase2, DefDatabase2Storage, InternDatabase, InternDatabaseStorage, RawItemsQuery,
-    RawItemsWithSourceMapQuery,
-};
+pub use hir_def::db::{InternDatabase, InternDatabaseStorage};
 pub use hir_expand::db::{
     AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery,
     ParseMacroQuery,
@@ -35,7 +32,7 @@ pub use hir_expand::db::{
 // This database uses `AstDatabase` internally,
 #[salsa::query_group(DefDatabaseStorage)]
 #[salsa::requires(AstDatabase)]
-pub trait DefDatabase: HirDebugDatabase + DefDatabase2 {
+pub trait DefDatabase: InternDatabase + HirDebugDatabase + AstDatabase {
     #[salsa::invoke(crate::adt::StructData::struct_data_query)]
     fn struct_data(&self, s: Struct) -> Arc<StructData>;
 
@@ -48,6 +45,15 @@ pub trait DefDatabase: HirDebugDatabase + DefDatabase2 {
     #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)]
     fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex;
 
+    #[salsa::invoke(RawItems::raw_items_with_source_map_query)]
+    fn raw_items_with_source_map(
+        &self,
+        file_id: HirFileId,
+    ) -> (Arc<RawItems>, Arc<ImportSourceMap>);
+
+    #[salsa::invoke(RawItems::raw_items_query)]
+    fn raw_items(&self, file_id: HirFileId) -> Arc<RawItems>;
+
     #[salsa::invoke(CrateDefMap::crate_def_map_query)]
     fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>;
 
diff --git a/crates/ra_hir_expand/src/either.rs b/crates/ra_hir/src/either.rs
similarity index 100%
rename from crates/ra_hir_expand/src/either.rs
rename to crates/ra_hir/src/either.rs
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs
index 6e23197a4d..d238741bab 100644
--- a/crates/ra_hir/src/expr.rs
+++ b/crates/ra_hir/src/expr.rs
@@ -6,17 +6,15 @@ pub(crate) mod validation;
 
 use std::{ops::Index, sync::Arc};
 
-use hir_def::{
-    path::GenericArgs,
-    type_ref::{Mutability, TypeRef},
-};
 use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
 use ra_syntax::{ast, AstPtr};
 use rustc_hash::FxHashMap;
 
 use crate::{
     db::HirDatabase,
+    path::GenericArgs,
     ty::primitive::{UncertainFloatTy, UncertainIntTy},
+    type_ref::{Mutability, TypeRef},
     DefWithBody, Either, HasSource, Name, Path, Resolver, Source,
 };
 
diff --git a/crates/ra_hir/src/expr/lower.rs b/crates/ra_hir/src/expr/lower.rs
index 6463dd65e1..b3a9a2e6b9 100644
--- a/crates/ra_hir/src/expr/lower.rs
+++ b/crates/ra_hir/src/expr/lower.rs
@@ -1,10 +1,5 @@
 //! FIXME: write short doc here
 
-use hir_def::{path::GenericArgs, type_ref::TypeRef};
-use hir_expand::{
-    hygiene::Hygiene,
-    name::{self, AsName, Name},
-};
 use ra_arena::Arena;
 use ra_syntax::{
     ast::{
@@ -17,7 +12,10 @@ use test_utils::tested_by;
 
 use crate::{
     db::HirDatabase,
+    name::{AsName, Name, SELF_PARAM},
+    path::GenericArgs,
     ty::primitive::{FloatTy, IntTy, UncertainFloatTy, UncertainIntTy},
+    type_ref::TypeRef,
     AstId, DefWithBody, Either, HirFileId, MacroCallLoc, MacroFileKind, Mutability, Path, Resolver,
     Source,
 };
@@ -80,7 +78,7 @@ where
                 let ptr = AstPtr::new(&self_param);
                 let param_pat = self.alloc_pat(
                     Pat::Bind {
-                        name: name::SELF_PARAM,
+                        name: SELF_PARAM,
                         mode: BindingAnnotation::Unannotated,
                         subpat: None,
                     },
@@ -597,8 +595,7 @@ where
     }
 
     fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
-        let hygiene = Hygiene::new(self.db, self.current_file_id);
-        Path::from_src(path, &hygiene)
+        Path::from_src(Source { ast: path, file_id: self.current_file_id }, self.db)
     }
 }
 
diff --git a/crates/ra_hir/src/expr/validation.rs b/crates/ra_hir/src/expr/validation.rs
index c685edda19..1aa853c3e9 100644
--- a/crates/ra_hir/src/expr/validation.rs
+++ b/crates/ra_hir/src/expr/validation.rs
@@ -2,7 +2,6 @@
 
 use std::sync::Arc;
 
-use hir_def::path::known;
 use ra_syntax::ast;
 use rustc_hash::FxHashSet;
 
@@ -10,6 +9,7 @@ use crate::{
     db::HirDatabase,
     diagnostics::{DiagnosticSink, MissingFields, MissingOkInTailExpr},
     expr::AstPtr,
+    path::known,
     ty::{ApplicationTy, InferenceResult, Ty, TypeCtor},
     Adt, Function, Name, Path,
 };
diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs
index a9de014553..93713bb142 100644
--- a/crates/ra_hir/src/from_source.rs
+++ b/crates/ra_hir/src/from_source.rs
@@ -1,11 +1,16 @@
 //! FIXME: write short doc here
 
-use hir_expand::name::AsName;
-use ra_syntax::ast::{self, AstNode, NameOwner};
+use ra_db::{FileId, FilePosition};
+use ra_syntax::{
+    algo::find_node_at_offset,
+    ast::{self, AstNode, NameOwner},
+    SyntaxNode,
+};
 
 use crate::{
     db::{AstDatabase, DefDatabase, HirDatabase},
     ids::{AstItemDef, LocationCtx},
+    name::AsName,
     AstId, Const, Crate, Enum, EnumVariant, FieldSource, Function, HasSource, ImplBlock, Module,
     ModuleSource, Source, Static, Struct, StructField, Trait, TypeAlias, Union, VariantDef,
 };
@@ -124,6 +129,41 @@ impl FromSource for StructField {
     }
 }
 
+// FIXME: simplify it
+impl ModuleSource {
+    pub fn from_position(
+        db: &(impl DefDatabase + AstDatabase),
+        position: FilePosition,
+    ) -> ModuleSource {
+        let parse = db.parse(position.file_id);
+        match &find_node_at_offset::<ast::Module>(parse.tree().syntax(), position.offset) {
+            Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
+            _ => {
+                let source_file = parse.tree();
+                ModuleSource::SourceFile(source_file)
+            }
+        }
+    }
+
+    pub fn from_child_node(
+        db: &(impl DefDatabase + AstDatabase),
+        file_id: FileId,
+        child: &SyntaxNode,
+    ) -> ModuleSource {
+        if let Some(m) = child.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi()) {
+            ModuleSource::Module(m)
+        } else {
+            let source_file = db.parse(file_id).tree();
+            ModuleSource::SourceFile(source_file)
+        }
+    }
+
+    pub fn from_file_id(db: &(impl DefDatabase + AstDatabase), file_id: FileId) -> ModuleSource {
+        let source_file = db.parse(file_id).tree();
+        ModuleSource::SourceFile(source_file)
+    }
+}
+
 impl Module {
     pub fn from_declaration(db: &impl HirDatabase, src: Source<ast::Module>) -> Option<Self> {
         let src_parent = Source {
diff --git a/crates/ra_hir/src/generics.rs b/crates/ra_hir/src/generics.rs
index 52e1fbf294..4ce7551c33 100644
--- a/crates/ra_hir/src/generics.rs
+++ b/crates/ra_hir/src/generics.rs
@@ -5,17 +5,15 @@
 
 use std::sync::Arc;
 
-use hir_def::{
-    path::Path,
-    type_ref::{TypeBound, TypeRef},
-};
-use hir_expand::name::{self, AsName};
 use ra_syntax::ast::{self, DefaultTypeParamOwner, NameOwner, TypeBoundsOwner, TypeParamsOwner};
 
 use crate::{
     db::{AstDatabase, DefDatabase, HirDatabase},
-    Adt, Const, Container, Enum, EnumVariant, Function, HasSource, ImplBlock, Name, Struct, Trait,
-    TypeAlias, Union,
+    name::SELF_TYPE,
+    path::Path,
+    type_ref::{TypeBound, TypeRef},
+    Adt, AsName, Const, Container, Enum, EnumVariant, Function, HasSource, ImplBlock, Name, Struct,
+    Trait, TypeAlias, Union,
 };
 
 /// Data about a generic parameter (to a function, struct, impl, ...).
@@ -96,15 +94,11 @@ impl GenericParams {
             GenericDef::Adt(Adt::Enum(it)) => generics.fill(&it.source(db).ast, start),
             GenericDef::Trait(it) => {
                 // traits get the Self type as an implicit first type parameter
-                generics.params.push(GenericParam {
-                    idx: start,
-                    name: name::SELF_TYPE,
-                    default: None,
-                });
+                generics.params.push(GenericParam { idx: start, name: SELF_TYPE, default: None });
                 generics.fill(&it.source(db).ast, start + 1);
                 // add super traits as bounds on Self
                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
-                let self_param = TypeRef::Path(name::SELF_TYPE.into());
+                let self_param = TypeRef::Path(SELF_TYPE.into());
                 generics.fill_bounds(&it.source(db).ast, self_param);
             }
             GenericDef::TypeAlias(it) => generics.fill(&it.source(db).ast, start),
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs
index b1a0140745..06f21fc33e 100644
--- a/crates/ra_hir/src/impl_block.rs
+++ b/crates/ra_hir/src/impl_block.rs
@@ -3,8 +3,6 @@
 use rustc_hash::FxHashMap;
 use std::sync::Arc;
 
-use hir_def::{attr::Attr, type_ref::TypeRef};
-use hir_expand::hygiene::Hygiene;
 use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
 use ra_cfg::CfgOptions;
 use ra_syntax::{
@@ -13,6 +11,7 @@ use ra_syntax::{
 };
 
 use crate::{
+    attr::Attr,
     code_model::{Module, ModuleSource},
     db::{AstDatabase, DefDatabase, HirDatabase},
     generics::HasGenericParams,
@@ -20,6 +19,7 @@ use crate::{
     ids::MacroCallLoc,
     resolve::Resolver,
     ty::Ty,
+    type_ref::TypeRef,
     AssocItem, AstId, Const, Function, HasSource, HirFileId, MacroFileKind, Path, Source, TraitRef,
     TypeAlias,
 };
@@ -228,11 +228,10 @@ impl ModuleImplBlocks {
         owner: &dyn ast::ModuleItemOwner,
         file_id: HirFileId,
     ) {
-        let hygiene = Hygiene::new(db, file_id);
         for item in owner.items_with_macros() {
             match item {
                 ast::ItemOrMacro::Item(ast::ModuleItem::ImplBlock(impl_block_ast)) => {
-                    let attrs = Attr::from_attrs_owner(&impl_block_ast, &hygiene);
+                    let attrs = Attr::from_attrs_owner(file_id, &impl_block_ast, db);
                     if attrs.map_or(false, |attrs| {
                         attrs.iter().any(|attr| attr.is_cfg_enabled(cfg_options) == Some(false))
                     }) {
@@ -249,7 +248,7 @@ impl ModuleImplBlocks {
                 }
                 ast::ItemOrMacro::Item(_) => (),
                 ast::ItemOrMacro::Macro(macro_call) => {
-                    let attrs = Attr::from_attrs_owner(&macro_call, &hygiene);
+                    let attrs = Attr::from_attrs_owner(file_id, &macro_call, db);
                     if attrs.map_or(false, |attrs| {
                         attrs.iter().any(|attr| attr.is_cfg_enabled(cfg_options) == Some(false))
                     }) {
@@ -258,8 +257,9 @@ impl ModuleImplBlocks {
 
                     //FIXME: we should really cut down on the boilerplate required to process a macro
                     let ast_id = AstId::new(file_id, db.ast_id_map(file_id).ast_id(&macro_call));
-                    if let Some(path) =
-                        macro_call.path().and_then(|path| Path::from_src(path, &hygiene))
+                    if let Some(path) = macro_call
+                        .path()
+                        .and_then(|path| Path::from_src(Source { ast: path, file_id }, db))
                     {
                         if let Some(def) = self.module.resolver(db).resolve_path_as_macro(db, &path)
                         {
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index 603b0c3dc3..0f2d233bb1 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -26,19 +26,24 @@ macro_rules! impl_froms {
     }
 }
 
+mod either;
 pub mod debug;
 
 pub mod db;
 #[macro_use]
 pub mod mock;
+mod path;
 pub mod source_binder;
 
 mod ids;
+mod name;
 mod nameres;
 mod adt;
 mod traits;
 mod type_alias;
+mod type_ref;
 mod ty;
+mod attr;
 mod impl_block;
 mod expr;
 mod lang_item;
@@ -54,34 +59,36 @@ pub mod from_source;
 #[cfg(test)]
 mod marks;
 
-use hir_expand::AstId;
+use hir_expand::{
+    ast_id_map::{AstIdMap, FileAstId},
+    AstId,
+};
 
-use crate::{ids::MacroFileKind, resolve::Resolver};
+use crate::{ids::MacroFileKind, name::AsName, resolve::Resolver};
 
 pub use crate::{
     adt::VariantDef,
-    code_model::{
-        docs::{DocDef, Docs, Documentation},
-        src::{HasBodySource, HasSource, Source},
-        Adt, AssocItem, BuiltinType, Const, ConstData, Container, Crate, CrateDependency,
-        DefWithBody, Enum, EnumVariant, FieldSource, FnData, Function, HasBody, MacroDef, Module,
-        ModuleDef, ModuleSource, Static, Struct, StructField, Trait, TypeAlias, Union,
-    },
+    either::Either,
     expr::ExprScopes,
     from_source::FromSource,
     generics::{GenericDef, GenericParam, GenericParams, HasGenericParams},
     ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile},
     impl_block::ImplBlock,
+    name::Name,
     nameres::{ImportId, Namespace, PerNs},
+    path::{Path, PathKind},
     resolve::ScopeDef,
     source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer},
     ty::{
         display::HirDisplay, ApplicationTy, CallableDef, Substs, TraitRef, Ty, TypeCtor, TypeWalk,
     },
+    type_ref::Mutability,
 };
 
-pub use hir_def::{
-    path::{Path, PathKind},
-    type_ref::Mutability,
+pub use self::code_model::{
+    docs::{DocDef, Docs, Documentation},
+    src::{HasBodySource, HasSource, Source},
+    Adt, AssocItem, BuiltinType, Const, ConstData, Container, Crate, CrateDependency, DefWithBody,
+    Enum, EnumVariant, FieldSource, FnData, Function, HasBody, MacroDef, Module, ModuleDef,
+    ModuleSource, Static, Struct, StructField, Trait, TypeAlias, Union,
 };
-pub use hir_expand::{either::Either, name::Name};
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs
index b423489a11..79af24b201 100644
--- a/crates/ra_hir/src/marks.rs
+++ b/crates/ra_hir/src/marks.rs
@@ -2,7 +2,6 @@
 
 test_utils::marks!(
     bogus_paths
-    // FIXME: restore this mark once hir is split
     name_res_works_for_broken_modules
     can_import_enum_variant
     type_var_cycles_resolve_completely
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs
index 35dfaf3bad..0b278deb3a 100644
--- a/crates/ra_hir/src/mock.rs
+++ b/crates/ra_hir/src/mock.rs
@@ -22,7 +22,6 @@ pub const WORKSPACE: SourceRootId = SourceRootId(0);
     db::InternDatabaseStorage,
     db::AstDatabaseStorage,
     db::DefDatabaseStorage,
-    db::DefDatabase2Storage,
     db::HirDatabaseStorage
 )]
 #[derive(Debug)]
diff --git a/crates/ra_hir_expand/src/name.rs b/crates/ra_hir/src/name.rs
similarity index 50%
rename from crates/ra_hir_expand/src/name.rs
rename to crates/ra_hir/src/name.rs
index 720896ee8e..1e0b8c3506 100644
--- a/crates/ra_hir_expand/src/name.rs
+++ b/crates/ra_hir/src/name.rs
@@ -33,7 +33,7 @@ impl Name {
         Name(Repr::Text(text))
     }
 
-    pub fn new_tuple_field(idx: usize) -> Name {
+    pub(crate) fn new_tuple_field(idx: usize) -> Name {
         Name(Repr::TupleField(idx))
     }
 
@@ -52,11 +52,11 @@ impl Name {
         }
     }
 
-    pub fn missing() -> Name {
+    pub(crate) fn missing() -> Name {
         Name::new_text("[missing name]".into())
     }
 
-    pub fn as_tuple_index(&self) -> Option<usize> {
+    pub(crate) fn as_tuple_index(&self) -> Option<usize> {
         match self.0 {
             Repr::TupleField(idx) => Some(idx),
             _ => None,
@@ -64,7 +64,7 @@ impl Name {
     }
 }
 
-pub trait AsName {
+pub(crate) trait AsName {
     fn as_name(&self) -> Name;
 }
 
@@ -99,44 +99,44 @@ impl AsName for ra_db::Dependency {
 }
 
 // Primitives
-pub const ISIZE: Name = Name::new_inline_ascii(5, b"isize");
-pub const I8: Name = Name::new_inline_ascii(2, b"i8");
-pub const I16: Name = Name::new_inline_ascii(3, b"i16");
-pub const I32: Name = Name::new_inline_ascii(3, b"i32");
-pub const I64: Name = Name::new_inline_ascii(3, b"i64");
-pub const I128: Name = Name::new_inline_ascii(4, b"i128");
-pub const USIZE: Name = Name::new_inline_ascii(5, b"usize");
-pub const U8: Name = Name::new_inline_ascii(2, b"u8");
-pub const U16: Name = Name::new_inline_ascii(3, b"u16");
-pub const U32: Name = Name::new_inline_ascii(3, b"u32");
-pub const U64: Name = Name::new_inline_ascii(3, b"u64");
-pub const U128: Name = Name::new_inline_ascii(4, b"u128");
-pub const F32: Name = Name::new_inline_ascii(3, b"f32");
-pub const F64: Name = Name::new_inline_ascii(3, b"f64");
-pub const BOOL: Name = Name::new_inline_ascii(4, b"bool");
-pub const CHAR: Name = Name::new_inline_ascii(4, b"char");
-pub const STR: Name = Name::new_inline_ascii(3, b"str");
+pub(crate) const ISIZE: Name = Name::new_inline_ascii(5, b"isize");
+pub(crate) const I8: Name = Name::new_inline_ascii(2, b"i8");
+pub(crate) const I16: Name = Name::new_inline_ascii(3, b"i16");
+pub(crate) const I32: Name = Name::new_inline_ascii(3, b"i32");
+pub(crate) const I64: Name = Name::new_inline_ascii(3, b"i64");
+pub(crate) const I128: Name = Name::new_inline_ascii(4, b"i128");
+pub(crate) const USIZE: Name = Name::new_inline_ascii(5, b"usize");
+pub(crate) const U8: Name = Name::new_inline_ascii(2, b"u8");
+pub(crate) const U16: Name = Name::new_inline_ascii(3, b"u16");
+pub(crate) const U32: Name = Name::new_inline_ascii(3, b"u32");
+pub(crate) const U64: Name = Name::new_inline_ascii(3, b"u64");
+pub(crate) const U128: Name = Name::new_inline_ascii(4, b"u128");
+pub(crate) const F32: Name = Name::new_inline_ascii(3, b"f32");
+pub(crate) const F64: Name = Name::new_inline_ascii(3, b"f64");
+pub(crate) const BOOL: Name = Name::new_inline_ascii(4, b"bool");
+pub(crate) const CHAR: Name = Name::new_inline_ascii(4, b"char");
+pub(crate) const STR: Name = Name::new_inline_ascii(3, b"str");
 
 // Special names
-pub const SELF_PARAM: Name = Name::new_inline_ascii(4, b"self");
-pub const SELF_TYPE: Name = Name::new_inline_ascii(4, b"Self");
-pub const MACRO_RULES: Name = Name::new_inline_ascii(11, b"macro_rules");
+pub(crate) const SELF_PARAM: Name = Name::new_inline_ascii(4, b"self");
+pub(crate) const SELF_TYPE: Name = Name::new_inline_ascii(4, b"Self");
+pub(crate) const MACRO_RULES: Name = Name::new_inline_ascii(11, b"macro_rules");
 
 // Components of known path (value or mod name)
-pub const STD: Name = Name::new_inline_ascii(3, b"std");
-pub const ITER: Name = Name::new_inline_ascii(4, b"iter");
-pub const OPS: Name = Name::new_inline_ascii(3, b"ops");
-pub const FUTURE: Name = Name::new_inline_ascii(6, b"future");
-pub const RESULT: Name = Name::new_inline_ascii(6, b"result");
-pub const BOXED: Name = Name::new_inline_ascii(5, b"boxed");
+pub(crate) const STD: Name = Name::new_inline_ascii(3, b"std");
+pub(crate) const ITER: Name = Name::new_inline_ascii(4, b"iter");
+pub(crate) const OPS: Name = Name::new_inline_ascii(3, b"ops");
+pub(crate) const FUTURE: Name = Name::new_inline_ascii(6, b"future");
+pub(crate) const RESULT: Name = Name::new_inline_ascii(6, b"result");
+pub(crate) const BOXED: Name = Name::new_inline_ascii(5, b"boxed");
 
 // Components of known path (type name)
-pub const INTO_ITERATOR_TYPE: Name = Name::new_inline_ascii(12, b"IntoIterator");
-pub const ITEM_TYPE: Name = Name::new_inline_ascii(4, b"Item");
-pub const TRY_TYPE: Name = Name::new_inline_ascii(3, b"Try");
-pub const OK_TYPE: Name = Name::new_inline_ascii(2, b"Ok");
-pub const FUTURE_TYPE: Name = Name::new_inline_ascii(6, b"Future");
-pub const RESULT_TYPE: Name = Name::new_inline_ascii(6, b"Result");
-pub const OUTPUT_TYPE: Name = Name::new_inline_ascii(6, b"Output");
-pub const TARGET_TYPE: Name = Name::new_inline_ascii(6, b"Target");
-pub const BOX_TYPE: Name = Name::new_inline_ascii(3, b"Box");
+pub(crate) const INTO_ITERATOR_TYPE: Name = Name::new_inline_ascii(12, b"IntoIterator");
+pub(crate) const ITEM_TYPE: Name = Name::new_inline_ascii(4, b"Item");
+pub(crate) const TRY_TYPE: Name = Name::new_inline_ascii(3, b"Try");
+pub(crate) const OK_TYPE: Name = Name::new_inline_ascii(2, b"Ok");
+pub(crate) const FUTURE_TYPE: Name = Name::new_inline_ascii(6, b"Future");
+pub(crate) const RESULT_TYPE: Name = Name::new_inline_ascii(6, b"Result");
+pub(crate) const OUTPUT_TYPE: Name = Name::new_inline_ascii(6, b"Output");
+pub(crate) const TARGET_TYPE: Name = Name::new_inline_ascii(6, b"Target");
+pub(crate) const BOX_TYPE: Name = Name::new_inline_ascii(3, b"Box");
diff --git a/crates/ra_hir/src/nameres.rs b/crates/ra_hir/src/nameres.rs
index 39f585b446..b325979f5b 100644
--- a/crates/ra_hir/src/nameres.rs
+++ b/crates/ra_hir/src/nameres.rs
@@ -48,6 +48,7 @@
 //! on the result
 
 mod per_ns;
+mod raw;
 mod collector;
 mod mod_resolution;
 #[cfg(test)]
@@ -73,9 +74,12 @@ use crate::{
     Trait,
 };
 
-pub use self::per_ns::{Namespace, PerNs};
+pub(crate) use self::raw::{ImportSourceMap, RawItems};
 
-pub use hir_def::nameres::raw::ImportId;
+pub use self::{
+    per_ns::{Namespace, PerNs},
+    raw::ImportId,
+};
 
 /// Contains all top-level defs from a macro-expanded crate
 #[derive(Debug, PartialEq, Eq)]
@@ -324,8 +328,7 @@ impl CrateDefMap {
     ) -> ResolvePathResult {
         let mut segments = path.segments.iter().enumerate();
         let mut curr_per_ns: PerNs = match path.kind {
-            PathKind::DollarCrate(crate_id) => {
-                let krate = Crate { crate_id };
+            PathKind::DollarCrate(krate) => {
                 if krate == self.krate {
                     tested_by!(macro_dollar_crate_self);
                     PerNs::types(Module::new(self.krate, self.root).into())
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs
index e2e13805ac..a94a0554c8 100644
--- a/crates/ra_hir/src/nameres/collector.rs
+++ b/crates/ra_hir/src/nameres/collector.rs
@@ -1,7 +1,5 @@
 //! FIXME: write short doc here
 
-use hir_def::{attr::Attr, nameres::raw};
-use hir_expand::name;
 use ra_cfg::CfgOptions;
 use ra_db::FileId;
 use ra_syntax::{ast, SmolStr};
@@ -9,10 +7,12 @@ use rustc_hash::FxHashMap;
 use test_utils::tested_by;
 
 use crate::{
+    attr::Attr,
     db::DefDatabase,
     ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind},
+    name::MACRO_RULES,
     nameres::{
-        diagnostics::DefDiagnostic, mod_resolution::ModDir, Crate, CrateDefMap, CrateModuleId,
+        diagnostics::DefDiagnostic, mod_resolution::ModDir, raw, Crate, CrateDefMap, CrateModuleId,
         ModuleData, ModuleDef, PerNs, ReachedFixedPoint, Resolution, ResolveMode,
     },
     Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static,
@@ -725,7 +725,7 @@ where
 }
 
 fn is_macro_rules(path: &Path) -> bool {
-    path.as_ident() == Some(&name::MACRO_RULES)
+    path.as_ident() == Some(&MACRO_RULES)
 }
 
 #[cfg(test)]
diff --git a/crates/ra_hir_def/src/nameres/raw.rs b/crates/ra_hir/src/nameres/raw.rs
similarity index 84%
rename from crates/ra_hir_def/src/nameres/raw.rs
rename to crates/ra_hir/src/nameres/raw.rs
index 86c05d6028..57f2929c38 100644
--- a/crates/ra_hir_def/src/nameres/raw.rs
+++ b/crates/ra_hir/src/nameres/raw.rs
@@ -2,20 +2,18 @@
 
 use std::{ops::Index, sync::Arc};
 
-use hir_expand::{
-    ast_id_map::AstIdMap,
-    db::AstDatabase,
-    either::Either,
-    hygiene::Hygiene,
-    name::{AsName, Name},
-};
 use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId};
 use ra_syntax::{
     ast::{self, AttrsOwner, NameOwner},
     AstNode, AstPtr, SourceFile,
 };
+use test_utils::tested_by;
 
-use crate::{attr::Attr, db::DefDatabase2, path::Path, FileAstId, HirFileId, ModuleSource, Source};
+use crate::{
+    attr::Attr,
+    db::{AstDatabase, DefDatabase},
+    AsName, AstIdMap, Either, FileAstId, HirFileId, ModuleSource, Name, Path, Source,
+};
 
 /// `RawItems` is a set of top-level items in a file (except for impls).
 ///
@@ -39,8 +37,10 @@ pub struct ImportSourceMap {
 type ImportSourcePtr = Either<AstPtr<ast::UseTree>, AstPtr<ast::ExternCrateItem>>;
 type ImportSource = Either<ast::UseTree, ast::ExternCrateItem>;
 
-fn to_node(ptr: ImportSourcePtr, file: &SourceFile) -> ImportSource {
-    ptr.map(|ptr| ptr.to_node(file.syntax()), |ptr| ptr.to_node(file.syntax()))
+impl ImportSourcePtr {
+    fn to_node(self, file: &SourceFile) -> ImportSource {
+        self.map(|ptr| ptr.to_node(file.syntax()), |ptr| ptr.to_node(file.syntax()))
+    }
 }
 
 impl ImportSourceMap {
@@ -48,26 +48,26 @@ impl ImportSourceMap {
         self.map.insert(import, ptr)
     }
 
-    pub fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource {
+    pub(crate) fn get(&self, source: &ModuleSource, import: ImportId) -> ImportSource {
         let file = match source {
             ModuleSource::SourceFile(file) => file.clone(),
             ModuleSource::Module(m) => m.syntax().ancestors().find_map(SourceFile::cast).unwrap(),
         };
 
-        to_node(self.map[import], &file)
+        self.map[import].to_node(&file)
     }
 }
 
 impl RawItems {
     pub(crate) fn raw_items_query(
-        db: &(impl DefDatabase2 + AstDatabase),
+        db: &(impl DefDatabase + AstDatabase),
         file_id: HirFileId,
     ) -> Arc<RawItems> {
         db.raw_items_with_source_map(file_id).0
     }
 
     pub(crate) fn raw_items_with_source_map_query(
-        db: &(impl DefDatabase2 + AstDatabase),
+        db: &(impl DefDatabase + AstDatabase),
         file_id: HirFileId,
     ) -> (Arc<RawItems>, Arc<ImportSourceMap>) {
         let mut collector = RawItemsCollector {
@@ -75,7 +75,7 @@ impl RawItems {
             source_ast_id_map: db.ast_id_map(file_id),
             source_map: ImportSourceMap::default(),
             file_id,
-            hygiene: Hygiene::new(db, file_id),
+            db,
         };
         if let Some(node) = db.parse_or_expand(file_id) {
             if let Some(source_file) = ast::SourceFile::cast(node.clone()) {
@@ -87,7 +87,7 @@ impl RawItems {
         (Arc::new(collector.raw_items), Arc::new(collector.source_map))
     }
 
-    pub fn items(&self) -> &[RawItem] {
+    pub(super) fn items(&self) -> &[RawItem] {
         &self.items
     }
 }
@@ -124,19 +124,19 @@ impl Index<Macro> for RawItems {
 type Attrs = Option<Arc<[Attr]>>;
 
 #[derive(Debug, PartialEq, Eq, Clone)]
-pub struct RawItem {
+pub(super) struct RawItem {
     attrs: Attrs,
-    pub kind: RawItemKind,
+    pub(super) kind: RawItemKind,
 }
 
 impl RawItem {
-    pub fn attrs(&self) -> &[Attr] {
+    pub(super) fn attrs(&self) -> &[Attr] {
         self.attrs.as_ref().map_or(&[], |it| &*it)
     }
 }
 
 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
-pub enum RawItemKind {
+pub(super) enum RawItemKind {
     Module(Module),
     Import(ImportId),
     Def(Def),
@@ -144,11 +144,11 @@ pub enum RawItemKind {
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct Module(RawId);
+pub(super) struct Module(RawId);
 impl_arena_id!(Module);
 
 #[derive(Debug, PartialEq, Eq)]
-pub enum ModuleData {
+pub(super) enum ModuleData {
     Declaration { name: Name, ast_id: FileAstId<ast::Module> },
     Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> },
 }
@@ -159,26 +159,26 @@ impl_arena_id!(ImportId);
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ImportData {
-    pub path: Path,
-    pub alias: Option<Name>,
-    pub is_glob: bool,
-    pub is_prelude: bool,
-    pub is_extern_crate: bool,
-    pub is_macro_use: bool,
+    pub(super) path: Path,
+    pub(super) alias: Option<Name>,
+    pub(super) is_glob: bool,
+    pub(super) is_prelude: bool,
+    pub(super) is_extern_crate: bool,
+    pub(super) is_macro_use: bool,
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct Def(RawId);
+pub(super) struct Def(RawId);
 impl_arena_id!(Def);
 
 #[derive(Debug, PartialEq, Eq)]
-pub struct DefData {
-    pub name: Name,
-    pub kind: DefKind,
+pub(super) struct DefData {
+    pub(super) name: Name,
+    pub(super) kind: DefKind,
 }
 
 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
-pub enum DefKind {
+pub(super) enum DefKind {
     Function(FileAstId<ast::FnDef>),
     Struct(FileAstId<ast::StructDef>),
     Union(FileAstId<ast::StructDef>),
@@ -190,26 +190,26 @@ pub enum DefKind {
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct Macro(RawId);
+pub(super) struct Macro(RawId);
 impl_arena_id!(Macro);
 
 #[derive(Debug, PartialEq, Eq)]
-pub struct MacroData {
-    pub ast_id: FileAstId<ast::MacroCall>,
-    pub path: Path,
-    pub name: Option<Name>,
-    pub export: bool,
+pub(super) struct MacroData {
+    pub(super) ast_id: FileAstId<ast::MacroCall>,
+    pub(super) path: Path,
+    pub(super) name: Option<Name>,
+    pub(super) export: bool,
 }
 
-struct RawItemsCollector {
+struct RawItemsCollector<DB> {
     raw_items: RawItems,
     source_ast_id_map: Arc<AstIdMap>,
     source_map: ImportSourceMap,
     file_id: HirFileId,
-    hygiene: Hygiene,
+    db: DB,
 }
 
-impl RawItemsCollector {
+impl<DB: AstDatabase> RawItemsCollector<&DB> {
     fn process_module(&mut self, current_module: Option<Module>, body: impl ast::ModuleItemOwner) {
         for item_or_macro in body.items_with_macros() {
             match item_or_macro {
@@ -297,8 +297,7 @@ impl RawItemsCollector {
             self.push_item(current_module, attrs, RawItemKind::Module(item));
             return;
         }
-        // FIXME: restore this mark once we complete hir splitting
-        // tested_by!(name_res_works_for_broken_modules);
+        tested_by!(name_res_works_for_broken_modules);
     }
 
     fn add_use_item(&mut self, current_module: Option<Module>, use_item: ast::UseItem) {
@@ -306,10 +305,9 @@ impl RawItemsCollector {
         let is_prelude = use_item.has_atom_attr("prelude_import");
         let attrs = self.parse_attrs(&use_item);
 
-        let mut buf = Vec::new();
         Path::expand_use_item(
             Source { ast: use_item, file_id: self.file_id },
-            &self.hygiene,
+            self.db,
             |path, use_tree, is_glob, alias| {
                 let import_data = ImportData {
                     path,
@@ -319,12 +317,14 @@ impl RawItemsCollector {
                     is_extern_crate: false,
                     is_macro_use: false,
                 };
-                buf.push((import_data, Either::A(AstPtr::new(use_tree))));
+                self.push_import(
+                    current_module,
+                    attrs.clone(),
+                    import_data,
+                    Either::A(AstPtr::new(use_tree)),
+                );
             },
-        );
-        for (import_data, ptr) in buf {
-            self.push_import(current_module, attrs.clone(), import_data, ptr);
-        }
+        )
     }
 
     fn add_extern_crate_item(
@@ -357,7 +357,10 @@ impl RawItemsCollector {
 
     fn add_macro(&mut self, current_module: Option<Module>, m: ast::MacroCall) {
         let attrs = self.parse_attrs(&m);
-        let path = match m.path().and_then(|path| Path::from_src(path, &self.hygiene)) {
+        let path = match m
+            .path()
+            .and_then(|path| Path::from_src(Source { ast: path, file_id: self.file_id }, self.db))
+        {
             Some(it) => it,
             _ => return,
         };
@@ -395,6 +398,6 @@ impl RawItemsCollector {
     }
 
     fn parse_attrs(&self, item: &impl ast::AttrsOwner) -> Attrs {
-        Attr::from_attrs_owner(item, &self.hygiene)
+        Attr::from_attrs_owner(self.file_id, item, self.db)
     }
 }
diff --git a/crates/ra_hir_def/src/path.rs b/crates/ra_hir/src/path.rs
similarity index 81%
rename from crates/ra_hir_def/src/path.rs
rename to crates/ra_hir/src/path.rs
index 04039376f3..bbe536bcb4 100644
--- a/crates/ra_hir_def/src/path.rs
+++ b/crates/ra_hir/src/path.rs
@@ -2,18 +2,12 @@
 
 use std::{iter, sync::Arc};
 
-use hir_expand::{
-    either::Either,
-    hygiene::Hygiene,
-    name::{self, AsName, Name},
-};
-use ra_db::CrateId;
 use ra_syntax::{
     ast::{self, NameOwner, TypeAscriptionOwner},
     AstNode,
 };
 
-use crate::{type_ref::TypeRef, Source};
+use crate::{db::AstDatabase, name, type_ref::TypeRef, AsName, Crate, Name, Source};
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
 pub struct Path {
@@ -61,18 +55,23 @@ pub enum PathKind {
     // Type based path like `<T>::foo`
     Type(Box<TypeRef>),
     // `$crate` from macro expansion
-    DollarCrate(CrateId),
+    DollarCrate(Crate),
 }
 
 impl Path {
     /// Calls `cb` with all paths, represented by this use item.
     pub fn expand_use_item(
         item_src: Source<ast::UseItem>,
-        hygiene: &Hygiene,
+        db: &impl AstDatabase,
         mut cb: impl FnMut(Path, &ast::UseTree, bool, Option<Name>),
     ) {
         if let Some(tree) = item_src.ast.use_tree() {
-            expand_use_tree(None, tree, hygiene, &mut cb);
+            expand_use_tree(
+                None,
+                tree,
+                &|| item_src.file_id.macro_crate(db).map(|crate_id| Crate { crate_id }),
+                &mut cb,
+            );
         }
     }
 
@@ -89,12 +88,17 @@ impl Path {
     /// Converts an `ast::Path` to `Path`. Works with use trees.
     /// DEPRECATED: It does not handle `$crate` from macro call.
     pub fn from_ast(path: ast::Path) -> Option<Path> {
-        Path::from_src(path, &Hygiene::new_unhygienic())
+        Path::parse(path, &|| None)
     }
 
     /// Converts an `ast::Path` to `Path`. Works with use trees.
     /// It correctly handles `$crate` based path from macro call.
-    pub fn from_src(mut path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
+    pub fn from_src(source: Source<ast::Path>, db: &impl AstDatabase) -> Option<Path> {
+        let file_id = source.file_id;
+        Path::parse(source.ast, &|| file_id.macro_crate(db).map(|crate_id| Crate { crate_id }))
+    }
+
+    fn parse(mut path: ast::Path, macro_crate: &impl Fn() -> Option<Crate>) -> Option<Path> {
         let mut kind = PathKind::Plain;
         let mut segments = Vec::new();
         loop {
@@ -105,28 +109,26 @@ impl Path {
             }
 
             match segment.kind()? {
-                ast::PathSegmentKind::Name(name_ref) => {
-                    // FIXME: this should just return name
-                    match hygiene.name_ref_to_name(name_ref) {
-                        Either::A(name) => {
-                            let args = segment
-                                .type_arg_list()
-                                .and_then(GenericArgs::from_ast)
-                                .or_else(|| {
-                                    GenericArgs::from_fn_like_path_ast(
-                                        segment.param_list(),
-                                        segment.ret_type(),
-                                    )
-                                })
-                                .map(Arc::new);
-                            let segment = PathSegment { name, args_and_bindings: args };
-                            segments.push(segment);
-                        }
-                        Either::B(crate_id) => {
-                            kind = PathKind::DollarCrate(crate_id);
+                ast::PathSegmentKind::Name(name) => {
+                    if name.text() == "$crate" {
+                        if let Some(macro_crate) = macro_crate() {
+                            kind = PathKind::DollarCrate(macro_crate);
                             break;
                         }
                     }
+
+                    let args = segment
+                        .type_arg_list()
+                        .and_then(GenericArgs::from_ast)
+                        .or_else(|| {
+                            GenericArgs::from_fn_like_path_ast(
+                                segment.param_list(),
+                                segment.ret_type(),
+                            )
+                        })
+                        .map(Arc::new);
+                    let segment = PathSegment { name: name.as_name(), args_and_bindings: args };
+                    segments.push(segment);
                 }
                 ast::PathSegmentKind::Type { type_ref, trait_ref } => {
                     assert!(path.qualifier().is_none()); // this can only occur at the first segment
@@ -140,7 +142,7 @@ impl Path {
                         }
                         // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
                         Some(trait_ref) => {
-                            let path = Path::from_src(trait_ref.path()?, hygiene)?;
+                            let path = Path::parse(trait_ref.path()?, macro_crate)?;
                             kind = path.kind;
                             let mut prefix_segments = path.segments;
                             prefix_segments.reverse();
@@ -227,7 +229,7 @@ impl Path {
 }
 
 impl GenericArgs {
-    pub fn from_ast(node: ast::TypeArgList) -> Option<GenericArgs> {
+    pub(crate) fn from_ast(node: ast::TypeArgList) -> Option<GenericArgs> {
         let mut args = Vec::new();
         for type_arg in node.type_args() {
             let type_ref = TypeRef::from_ast_opt(type_arg.type_ref());
@@ -291,8 +293,8 @@ impl From<Name> for Path {
 fn expand_use_tree(
     prefix: Option<Path>,
     tree: ast::UseTree,
-    hygiene: &Hygiene,
-    cb: &mut dyn FnMut(Path, &ast::UseTree, bool, Option<Name>),
+    macro_crate: &impl Fn() -> Option<Crate>,
+    cb: &mut impl FnMut(Path, &ast::UseTree, bool, Option<Name>),
 ) {
     if let Some(use_tree_list) = tree.use_tree_list() {
         let prefix = match tree.path() {
@@ -300,13 +302,13 @@ fn expand_use_tree(
             None => prefix,
             // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
             // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
-            Some(path) => match convert_path(prefix, path, hygiene) {
+            Some(path) => match convert_path(prefix, path, macro_crate) {
                 Some(it) => Some(it),
                 None => return, // FIXME: report errors somewhere
             },
         };
         for child_tree in use_tree_list.use_trees() {
-            expand_use_tree(prefix.clone(), child_tree, hygiene, cb);
+            expand_use_tree(prefix.clone(), child_tree, macro_crate, cb);
         }
     } else {
         let alias = tree.alias().and_then(|a| a.name()).map(|a| a.as_name());
@@ -323,7 +325,7 @@ fn expand_use_tree(
                     }
                 }
             }
-            if let Some(path) = convert_path(prefix, ast_path, hygiene) {
+            if let Some(path) = convert_path(prefix, ast_path, macro_crate) {
                 let is_glob = tree.has_star();
                 cb(path, &tree, is_glob, alias)
             }
@@ -333,36 +335,37 @@ fn expand_use_tree(
     }
 }
 
-fn convert_path(prefix: Option<Path>, path: ast::Path, hygiene: &Hygiene) -> Option<Path> {
+fn convert_path(
+    prefix: Option<Path>,
+    path: ast::Path,
+    macro_crate: &impl Fn() -> Option<Crate>,
+) -> Option<Path> {
     let prefix = if let Some(qual) = path.qualifier() {
-        Some(convert_path(prefix, qual, hygiene)?)
+        Some(convert_path(prefix, qual, macro_crate)?)
     } else {
         prefix
     };
 
     let segment = path.segment()?;
     let res = match segment.kind()? {
-        ast::PathSegmentKind::Name(name_ref) => {
-            match hygiene.name_ref_to_name(name_ref) {
-                Either::A(name) => {
-                    // no type args in use
-                    let mut res = prefix.unwrap_or_else(|| Path {
-                        kind: PathKind::Plain,
-                        segments: Vec::with_capacity(1),
-                    });
-                    res.segments.push(PathSegment {
-                        name,
-                        args_and_bindings: None, // no type args in use
-                    });
-                    res
-                }
-                Either::B(crate_id) => {
+        ast::PathSegmentKind::Name(name) => {
+            if name.text() == "$crate" {
+                if let Some(krate) = macro_crate() {
                     return Some(Path::from_simple_segments(
-                        PathKind::DollarCrate(crate_id),
+                        PathKind::DollarCrate(krate),
                         iter::empty(),
-                    ))
+                    ));
                 }
             }
+
+            // no type args in use
+            let mut res = prefix
+                .unwrap_or_else(|| Path { kind: PathKind::Plain, segments: Vec::with_capacity(1) });
+            res.segments.push(PathSegment {
+                name: name.as_name(),
+                args_and_bindings: None, // no type args in use
+            });
+            res
         }
         ast::PathSegmentKind::CrateKw => {
             if prefix.is_some() {
@@ -391,9 +394,8 @@ fn convert_path(prefix: Option<Path>, path: ast::Path, hygiene: &Hygiene) -> Opt
 }
 
 pub mod known {
-    use hir_expand::name;
-
     use super::{Path, PathKind};
+    use crate::name;
 
     pub fn std_iter_into_iterator() -> Path {
         Path::from_simple_segments(
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs
index f77c9df9f0..8b62694075 100644
--- a/crates/ra_hir/src/resolve.rs
+++ b/crates/ra_hir/src/resolve.rs
@@ -1,11 +1,7 @@
 //! Name resolution.
 use std::sync::Arc;
 
-use hir_def::{
-    path::{Path, PathKind},
-    CrateModuleId,
-};
-use hir_expand::name::{self, Name};
+use hir_def::CrateModuleId;
 use rustc_hash::FxHashSet;
 
 use crate::{
@@ -17,7 +13,9 @@ use crate::{
     },
     generics::GenericParams,
     impl_block::ImplBlock,
+    name::{Name, SELF_PARAM, SELF_TYPE},
     nameres::{CrateDefMap, PerNs},
+    path::{Path, PathKind},
     Adt, BuiltinType, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct,
     Trait, TypeAlias,
 };
@@ -152,13 +150,13 @@ impl Resolver {
                     }
                 }
                 Scope::ImplBlockScope(impl_) => {
-                    if first_name == &name::SELF_TYPE {
+                    if first_name == &SELF_TYPE {
                         let idx = if path.segments.len() == 1 { None } else { Some(1) };
                         return Some((TypeNs::SelfType(*impl_), idx));
                     }
                 }
                 Scope::AdtScope(adt) => {
-                    if first_name == &name::SELF_TYPE {
+                    if first_name == &SELF_TYPE {
                         let idx = if path.segments.len() == 1 { None } else { Some(1) };
                         return Some((TypeNs::AdtSelfType(*adt), idx));
                     }
@@ -207,7 +205,7 @@ impl Resolver {
             return None;
         }
         let n_segments = path.segments.len();
-        let tmp = name::SELF_PARAM;
+        let tmp = SELF_PARAM;
         let first_name = if path.is_self() { &tmp } else { &path.segments.first()?.name };
         let skip_to_mod = path.kind != PathKind::Plain && !path.is_self();
         for scope in self.scopes.iter().rev() {
@@ -243,13 +241,13 @@ impl Resolver {
                 Scope::GenericParams(_) => continue,
 
                 Scope::ImplBlockScope(impl_) if n_segments > 1 => {
-                    if first_name == &name::SELF_TYPE {
+                    if first_name == &SELF_TYPE {
                         let ty = TypeNs::SelfType(*impl_);
                         return Some(ResolveValueResult::Partial(ty, 1));
                     }
                 }
                 Scope::AdtScope(adt) if n_segments > 1 => {
-                    if first_name == &name::SELF_TYPE {
+                    if first_name == &SELF_TYPE {
                         let ty = TypeNs::AdtSelfType(*adt);
                         return Some(ResolveValueResult::Partial(ty, 1));
                     }
@@ -461,10 +459,10 @@ impl Scope {
                 }
             }
             Scope::ImplBlockScope(i) => {
-                f(name::SELF_TYPE, ScopeDef::ImplSelfType(*i));
+                f(SELF_TYPE, ScopeDef::ImplSelfType(*i));
             }
             Scope::AdtScope(i) => {
-                f(name::SELF_TYPE, ScopeDef::AdtSelfType(*i));
+                f(SELF_TYPE, ScopeDef::AdtSelfType(*i));
             }
             Scope::ExprScope(e) => {
                 e.expr_scopes.entries(e.scope_id).iter().for_each(|e| {
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 01f51ba5d4..730c332264 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -7,8 +7,6 @@
 //! purely for "IDE needs".
 use std::sync::Arc;
 
-use hir_def::path::known;
-use hir_expand::name::AsName;
 use ra_db::FileId;
 use ra_syntax::{
     ast::{self, AstNode},
@@ -26,10 +24,11 @@ use crate::{
         BodySourceMap,
     },
     ids::LocationCtx,
+    path::known,
     resolve::{ScopeDef, TypeNs, ValueNs},
     ty::method_resolution::implements_trait,
-    Const, DefWithBody, Either, Enum, FromSource, Function, HasBody, HirFileId, MacroDef, Module,
-    Name, Path, Resolver, Static, Struct, Ty,
+    AsName, Const, DefWithBody, Either, Enum, FromSource, Function, HasBody, HirFileId, MacroDef,
+    Module, Name, Path, Resolver, Static, Struct, Ty,
 };
 
 fn try_get_resolver_for_node(
diff --git a/crates/ra_hir/src/traits.rs b/crates/ra_hir/src/traits.rs
index 1a45dacba9..22f1880493 100644
--- a/crates/ra_hir/src/traits.rs
+++ b/crates/ra_hir/src/traits.rs
@@ -1,15 +1,14 @@
 //! HIR for trait definitions.
 
+use rustc_hash::FxHashMap;
 use std::sync::Arc;
 
-use hir_expand::name::AsName;
-
 use ra_syntax::ast::{self, NameOwner};
-use rustc_hash::FxHashMap;
 
 use crate::{
     db::{AstDatabase, DefDatabase},
     ids::LocationCtx,
+    name::AsName,
     AssocItem, Const, Function, HasSource, Module, Name, Trait, TypeAlias,
 };
 
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index d2bfcdc7db..cc9746f6d7 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -17,8 +17,8 @@ use std::sync::Arc;
 use std::{fmt, iter, mem};
 
 use crate::{
-    db::HirDatabase, expr::ExprId, util::make_mut_slice, Adt, Crate, DefWithBody, GenericParams,
-    HasGenericParams, Mutability, Name, Trait, TypeAlias,
+    db::HirDatabase, expr::ExprId, type_ref::Mutability, util::make_mut_slice, Adt, Crate,
+    DefWithBody, GenericParams, HasGenericParams, Name, Trait, TypeAlias,
 };
 use display::{HirDisplay, HirFormatter};
 
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir/src/ty/autoderef.rs
index 3645ee831c..02492ca145 100644
--- a/crates/ra_hir/src/ty/autoderef.rs
+++ b/crates/ra_hir/src/ty/autoderef.rs
@@ -5,11 +5,10 @@
 
 use std::iter::successors;
 
-use hir_expand::name;
 use log::{info, warn};
 
 use super::{traits::Solution, Canonical, Substs, Ty, TypeWalk};
-use crate::{db::HirDatabase, HasGenericParams, Resolver};
+use crate::{db::HirDatabase, name, HasGenericParams, Resolver};
 
 const AUTODEREF_RECURSION_LIMIT: usize = 10;
 
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs
index 6694467a36..ebaff998ee 100644
--- a/crates/ra_hir/src/ty/infer.rs
+++ b/crates/ra_hir/src/ty/infer.rs
@@ -21,11 +21,6 @@ use std::sync::Arc;
 use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
 use rustc_hash::FxHashMap;
 
-use hir_def::{
-    path::known,
-    type_ref::{Mutability, TypeRef},
-};
-use hir_expand::name;
 use ra_arena::map::ArenaMap;
 use ra_prof::profile;
 use test_utils::tested_by;
@@ -42,8 +37,11 @@ use crate::{
     db::HirDatabase,
     diagnostics::DiagnosticSink,
     expr::{BindingAnnotation, Body, ExprId, PatId},
+    name,
+    path::known,
     resolve::{Resolver, TypeNs},
     ty::infer::diagnostics::InferenceDiagnostic,
+    type_ref::{Mutability, TypeRef},
     Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Path, StructField,
 };
 
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs
index 6ea135126a..0429a98664 100644
--- a/crates/ra_hir/src/ty/infer/coerce.rs
+++ b/crates/ra_hir/src/ty/infer/coerce.rs
@@ -14,7 +14,8 @@ use crate::{
     lang_item::LangItemTarget,
     resolve::Resolver,
     ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk},
-    Adt, Mutability,
+    type_ref::Mutability,
+    Adt,
 };
 
 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs
index fed52df39c..f8807c7428 100644
--- a/crates/ra_hir/src/ty/infer/expr.rs
+++ b/crates/ra_hir/src/ty/infer/expr.rs
@@ -3,15 +3,14 @@
 use std::iter::{repeat, repeat_with};
 use std::sync::Arc;
 
-use hir_def::path::{GenericArg, GenericArgs};
-use hir_expand::name;
-
 use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
 use crate::{
     db::HirDatabase,
     expr::{self, Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp},
     generics::{GenericParams, HasGenericParams},
+    name,
     nameres::Namespace,
+    path::{GenericArg, GenericArgs},
     ty::{
         autoderef, method_resolution, op, primitive, CallableDef, InferTy, Mutability, Obligation,
         ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk,
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs
index 77aa35ce13..db979353a0 100644
--- a/crates/ra_hir/src/ty/infer/path.rs
+++ b/crates/ra_hir/src/ty/infer/path.rs
@@ -1,7 +1,5 @@
 //! Path expression resolution.
 
-use hir_def::path::PathSegment;
-
 use super::{ExprOrPatId, InferenceContext, TraitRef};
 use crate::{
     db::HirDatabase,
@@ -133,7 +131,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
     fn resolve_trait_assoc_item(
         &mut self,
         trait_ref: TraitRef,
-        segment: &PathSegment,
+        segment: &crate::path::PathSegment,
         id: ExprOrPatId,
     ) -> Option<(ValueNs, Option<Substs>)> {
         let trait_ = trait_ref.trait_;
@@ -172,7 +170,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
     fn resolve_ty_assoc_item(
         &mut self,
         ty: Ty,
-        segment: &PathSegment,
+        segment: &crate::path::PathSegment,
         id: ExprOrPatId,
     ) -> Option<(ValueNs, Option<Substs>)> {
         if let Ty::Unknown = ty {
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs
index 0f49a0e541..366556134b 100644
--- a/crates/ra_hir/src/ty/lower.rs
+++ b/crates/ra_hir/src/ty/lower.rs
@@ -8,11 +8,6 @@
 use std::iter;
 use std::sync::Arc;
 
-use hir_def::{
-    path::{GenericArg, PathSegment},
-    type_ref::{TypeBound, TypeRef},
-};
-
 use super::{
     FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor,
     TypeWalk,
@@ -23,8 +18,10 @@ use crate::{
     generics::HasGenericParams,
     generics::{GenericDef, WherePredicate},
     nameres::Namespace,
+    path::{GenericArg, PathSegment},
     resolve::{Resolver, TypeNs},
     ty::Adt,
+    type_ref::{TypeBound, TypeRef},
     util::make_mut_slice,
     BuiltinType, Const, Enum, EnumVariant, Function, ModuleDef, Path, Static, Struct, StructField,
     Trait, TypeAlias, Union,
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs
index eb69344f6a..50583a1429 100644
--- a/crates/ra_hir/src/ty/method_resolution.rs
+++ b/crates/ra_hir/src/ty/method_resolution.rs
@@ -15,7 +15,8 @@ use crate::{
     resolve::Resolver,
     ty::primitive::{FloatBitness, UncertainFloatTy, UncertainIntTy},
     ty::{Ty, TypeCtor},
-    AssocItem, Crate, Function, Module, Mutability, Name, Trait,
+    type_ref::Mutability,
+    AssocItem, Crate, Function, Module, Name, Trait,
 };
 
 /// This is used as a key for indexing impls.
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs
index 39ef921827..ab66515bee 100644
--- a/crates/ra_hir/src/ty/traits/chalk.rs
+++ b/crates/ra_hir/src/ty/traits/chalk.rs
@@ -9,8 +9,6 @@ use chalk_ir::{
 };
 use chalk_rust_ir::{AssociatedTyDatum, ImplDatum, StructDatum, TraitDatum};
 
-use hir_expand::name;
-
 use ra_db::salsa::{InternId, InternKey};
 
 use super::{Canonical, ChalkContext, Impl, Obligation};
@@ -736,7 +734,7 @@ fn closure_fn_trait_impl_datum(
         substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(),
     };
 
-    let output_ty_id = fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?;
+    let output_ty_id = fn_once_trait.associated_type_by_name(db, &crate::name::OUTPUT_TYPE)?;
 
     let output_ty_value = chalk_rust_ir::AssociatedTyValue {
         associated_ty_id: output_ty_id.to_chalk(db),
diff --git a/crates/ra_hir/src/type_alias.rs b/crates/ra_hir/src/type_alias.rs
index 078e6295ea..674a461020 100644
--- a/crates/ra_hir/src/type_alias.rs
+++ b/crates/ra_hir/src/type_alias.rs
@@ -2,13 +2,12 @@
 
 use std::sync::Arc;
 
-use hir_def::type_ref::TypeRef;
-use hir_expand::name::{AsName, Name};
-
 use ra_syntax::ast::NameOwner;
 
 use crate::{
     db::{AstDatabase, DefDatabase},
+    name::{AsName, Name},
+    type_ref::TypeRef,
     HasSource, TypeAlias,
 };
 
diff --git a/crates/ra_hir_def/src/type_ref.rs b/crates/ra_hir/src/type_ref.rs
similarity index 96%
rename from crates/ra_hir_def/src/type_ref.rs
rename to crates/ra_hir/src/type_ref.rs
index 8af061116d..2cf06b2504 100644
--- a/crates/ra_hir_def/src/type_ref.rs
+++ b/crates/ra_hir/src/type_ref.rs
@@ -3,7 +3,7 @@
 
 use ra_syntax::ast::{self, TypeAscriptionOwner, TypeBoundsOwner};
 
-use crate::path::Path;
+use crate::Path;
 
 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
 pub enum Mutability {
@@ -64,7 +64,7 @@ pub enum TypeBound {
 
 impl TypeRef {
     /// Converts an `ast::TypeRef` to a `hir::TypeRef`.
-    pub fn from_ast(node: ast::TypeRef) -> Self {
+    pub(crate) fn from_ast(node: ast::TypeRef) -> Self {
         match node {
             ast::TypeRef::ParenType(inner) => TypeRef::from_ast_opt(inner.type_ref()),
             ast::TypeRef::TupleType(inner) => {
@@ -113,7 +113,7 @@ impl TypeRef {
         }
     }
 
-    pub fn from_ast_opt(node: Option<ast::TypeRef>) -> Self {
+    pub(crate) fn from_ast_opt(node: Option<ast::TypeRef>) -> Self {
         if let Some(node) = node {
             TypeRef::from_ast(node)
         } else {
@@ -135,7 +135,7 @@ pub(crate) fn type_bounds_from_ast(type_bounds_opt: Option<ast::TypeBoundList>)
 }
 
 impl TypeBound {
-    pub fn from_ast(node: ast::TypeBound) -> Self {
+    pub(crate) fn from_ast(node: ast::TypeBound) -> Self {
         match node.kind() {
             ast::TypeBoundKind::PathType(path_type) => {
                 let path = match path_type.path() {
diff --git a/crates/ra_hir_def/Cargo.toml b/crates/ra_hir_def/Cargo.toml
index 746c907e80..75e93f2547 100644
--- a/crates/ra_hir_def/Cargo.toml
+++ b/crates/ra_hir_def/Cargo.toml
@@ -6,16 +6,9 @@ authors = ["rust-analyzer developers"]
 
 [dependencies]
 log = "0.4.5"
-once_cell = "1.0.1"
-relative-path = "1.0.0"
-rustc-hash = "1.0"
 
 ra_arena = { path = "../ra_arena" }
 ra_db = { path = "../ra_db" }
 ra_syntax = { path = "../ra_syntax" }
 ra_prof = { path = "../ra_prof" }
 hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
-test_utils = { path = "../test_utils" }
-mbe = { path = "../ra_mbe", package = "ra_mbe" }
-ra_cfg = { path = "../ra_cfg" }
-tt = { path = "../ra_tt", package = "ra_tt" }
diff --git a/crates/ra_hir_def/src/db.rs b/crates/ra_hir_def/src/db.rs
index b271636b07..f6f976c860 100644
--- a/crates/ra_hir_def/src/db.rs
+++ b/crates/ra_hir_def/src/db.rs
@@ -1,12 +1,8 @@
 //! Defines database & queries for name resolution.
-use std::sync::Arc;
 
-use hir_expand::{db::AstDatabase, HirFileId};
 use ra_db::{salsa, SourceDatabase};
 use ra_syntax::ast;
 
-use crate::nameres::raw::{ImportSourceMap, RawItems};
-
 #[salsa::query_group(InternDatabaseStorage)]
 pub trait InternDatabase: SourceDatabase {
     #[salsa::interned]
@@ -14,8 +10,6 @@ pub trait InternDatabase: SourceDatabase {
     #[salsa::interned]
     fn intern_struct(&self, loc: crate::ItemLoc<ast::StructDef>) -> crate::StructId;
     #[salsa::interned]
-    fn intern_union(&self, loc: crate::ItemLoc<ast::StructDef>) -> crate::UnionId;
-    #[salsa::interned]
     fn intern_enum(&self, loc: crate::ItemLoc<ast::EnumDef>) -> crate::EnumId;
     #[salsa::interned]
     fn intern_const(&self, loc: crate::ItemLoc<ast::ConstDef>) -> crate::ConstId;
@@ -26,15 +20,3 @@ pub trait InternDatabase: SourceDatabase {
     #[salsa::interned]
     fn intern_type_alias(&self, loc: crate::ItemLoc<ast::TypeAliasDef>) -> crate::TypeAliasId;
 }
-
-#[salsa::query_group(DefDatabase2Storage)]
-pub trait DefDatabase2: InternDatabase + AstDatabase {
-    #[salsa::invoke(RawItems::raw_items_with_source_map_query)]
-    fn raw_items_with_source_map(
-        &self,
-        file_id: HirFileId,
-    ) -> (Arc<RawItems>, Arc<ImportSourceMap>);
-
-    #[salsa::invoke(RawItems::raw_items_query)]
-    fn raw_items(&self, file_id: HirFileId) -> Arc<RawItems>;
-}
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
index 7a6c7b3012..4d6b9db033 100644
--- a/crates/ra_hir_def/src/lib.rs
+++ b/crates/ra_hir_def/src/lib.rs
@@ -8,18 +8,12 @@
 //! actually true.
 
 pub mod db;
-pub mod attr;
-pub mod path;
-pub mod type_ref;
-
-// FIXME: this should be private
-pub mod nameres;
 
 use std::hash::{Hash, Hasher};
 
 use hir_expand::{ast_id_map::FileAstId, db::AstDatabase, AstId, HirFileId};
 use ra_arena::{impl_arena_id, RawId};
-use ra_db::{salsa, CrateId, FileId};
+use ra_db::{salsa, CrateId};
 use ra_syntax::{ast, AstNode, SyntaxNode};
 
 use crate::db::InternDatabase;
@@ -30,68 +24,6 @@ pub struct Source<T> {
     pub ast: T,
 }
 
-pub enum ModuleSource {
-    SourceFile(ast::SourceFile),
-    Module(ast::Module),
-}
-
-impl ModuleSource {
-    pub fn new(
-        db: &impl db::DefDatabase2,
-        file_id: Option<FileId>,
-        decl_id: Option<AstId<ast::Module>>,
-    ) -> ModuleSource {
-        match (file_id, decl_id) {
-            (Some(file_id), _) => {
-                let source_file = db.parse(file_id).tree();
-                ModuleSource::SourceFile(source_file)
-            }
-            (None, Some(item_id)) => {
-                let module = item_id.to_node(db);
-                assert!(module.item_list().is_some(), "expected inline module");
-                ModuleSource::Module(module)
-            }
-            (None, None) => panic!(),
-        }
-    }
-
-    // FIXME: this methods do not belong here
-    pub fn from_position(
-        db: &impl db::DefDatabase2,
-        position: ra_db::FilePosition,
-    ) -> ModuleSource {
-        let parse = db.parse(position.file_id);
-        match &ra_syntax::algo::find_node_at_offset::<ast::Module>(
-            parse.tree().syntax(),
-            position.offset,
-        ) {
-            Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
-            _ => {
-                let source_file = parse.tree();
-                ModuleSource::SourceFile(source_file)
-            }
-        }
-    }
-
-    pub fn from_child_node(
-        db: &impl db::DefDatabase2,
-        file_id: FileId,
-        child: &SyntaxNode,
-    ) -> ModuleSource {
-        if let Some(m) = child.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi()) {
-            ModuleSource::Module(m)
-        } else {
-            let source_file = db.parse(file_id).tree();
-            ModuleSource::SourceFile(source_file)
-        }
-    }
-
-    pub fn from_file_id(db: &impl db::DefDatabase2, file_id: FileId) -> ModuleSource {
-        let source_file = db.parse(file_id).tree();
-        ModuleSource::SourceFile(source_file)
-    }
-}
-
 impl<T> Source<T> {
     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> Source<U> {
         Source { file_id: self.file_id, ast: f(self.ast) }
@@ -223,18 +155,6 @@ impl AstItemDef<ast::StructDef> for StructId {
     }
 }
 
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct UnionId(salsa::InternId);
-impl_intern_key!(UnionId);
-impl AstItemDef<ast::StructDef> for UnionId {
-    fn intern(db: &impl InternDatabase, loc: ItemLoc<ast::StructDef>) -> Self {
-        db.intern_union(loc)
-    }
-    fn lookup_intern(self, db: &impl InternDatabase) -> ItemLoc<ast::StructDef> {
-        db.lookup_intern_union(self)
-    }
-}
-
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub struct EnumId(salsa::InternId);
 impl_intern_key!(EnumId);
@@ -247,17 +167,6 @@ impl AstItemDef<ast::EnumDef> for EnumId {
     }
 }
 
-// FIXME: rename to `VariantId`, only enums can ave variants
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub struct EnumVariantId {
-    parent: EnumId,
-    local_id: LocalEnumVariantId,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-pub(crate) struct LocalEnumVariantId(RawId);
-impl_arena_id!(LocalEnumVariantId);
-
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub struct ConstId(salsa::InternId);
 impl_intern_key!(ConstId);
diff --git a/crates/ra_hir_def/src/nameres.rs b/crates/ra_hir_def/src/nameres.rs
deleted file mode 100644
index 5893708e8b..0000000000
--- a/crates/ra_hir_def/src/nameres.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-//! FIXME: write short doc here
-
-pub mod raw;
diff --git a/crates/ra_hir_expand/src/hygiene.rs b/crates/ra_hir_expand/src/hygiene.rs
deleted file mode 100644
index 77428ec990..0000000000
--- a/crates/ra_hir_expand/src/hygiene.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-//! This modules handles hygiene information.
-//!
-//! Specifically, `ast` + `Hygiene` allows you to create a `Name`. Note that, at
-//! this moment, this is horribly incomplete and handles only `$crate`.
-use ra_db::CrateId;
-use ra_syntax::ast;
-
-use crate::{
-    db::AstDatabase,
-    either::Either,
-    name::{AsName, Name},
-    HirFileId, HirFileIdRepr,
-};
-
-#[derive(Debug)]
-pub struct Hygiene {
-    // This is what `$crate` expands to
-    def_crate: Option<CrateId>,
-}
-
-impl Hygiene {
-    pub fn new(db: &impl AstDatabase, file_id: HirFileId) -> Hygiene {
-        let def_crate = match file_id.0 {
-            HirFileIdRepr::FileId(_) => None,
-            HirFileIdRepr::MacroFile(macro_file) => {
-                let loc = db.lookup_intern_macro(macro_file.macro_call_id);
-                Some(loc.def.krate)
-            }
-        };
-        Hygiene { def_crate }
-    }
-
-    pub fn new_unhygienic() -> Hygiene {
-        Hygiene { def_crate: None }
-    }
-
-    // FIXME: this should just return name
-    pub fn name_ref_to_name(&self, name_ref: ast::NameRef) -> Either<Name, CrateId> {
-        if let Some(def_crate) = self.def_crate {
-            if name_ref.text() == "$crate" {
-                return Either::B(def_crate);
-            }
-        }
-        Either::A(name_ref.as_name())
-    }
-}
diff --git a/crates/ra_hir_expand/src/lib.rs b/crates/ra_hir_expand/src/lib.rs
index 5a0e5a19c5..6b35386730 100644
--- a/crates/ra_hir_expand/src/lib.rs
+++ b/crates/ra_hir_expand/src/lib.rs
@@ -6,16 +6,13 @@
 
 pub mod db;
 pub mod ast_id_map;
-pub mod either;
-pub mod name;
-pub mod hygiene;
 
 use std::hash::{Hash, Hasher};
 
 use ra_db::{salsa, CrateId, FileId};
 use ra_syntax::ast::{self, AstNode};
 
-use crate::ast_id_map::FileAstId;
+use crate::{ast_id_map::FileAstId, db::AstDatabase};
 
 /// Input to the analyzer is a set of files, where each file is identified by
 /// `FileId` and contains source code. However, another source of source code in
@@ -53,7 +50,7 @@ impl From<MacroFile> for HirFileId {
 impl HirFileId {
     /// For macro-expansion files, returns the file original source file the
     /// expansion originated from.
-    pub fn original_file(self, db: &dyn db::AstDatabase) -> FileId {
+    pub fn original_file(self, db: &dyn AstDatabase) -> FileId {
         match self.0 {
             HirFileIdRepr::FileId(file_id) => file_id,
             HirFileIdRepr::MacroFile(macro_file) => {
@@ -62,6 +59,17 @@ impl HirFileId {
             }
         }
     }
+
+    /// Get the crate which the macro lives in, if it is a macro file.
+    pub fn macro_crate(self, db: &dyn AstDatabase) -> Option<CrateId> {
+        match self.0 {
+            HirFileIdRepr::FileId(_) => None,
+            HirFileIdRepr::MacroFile(macro_file) => {
+                let loc = db.lookup_intern_macro(macro_file.macro_call_id);
+                Some(loc.def.krate)
+            }
+        }
+    }
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -146,7 +154,7 @@ impl<N: AstNode> AstId<N> {
         self.file_id
     }
 
-    pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
+    pub fn to_node(&self, db: &dyn AstDatabase) -> N {
         let root = db.parse_or_expand(self.file_id).unwrap();
         db.ast_id_map(self.file_id).get(self.file_ast_id).to_node(&root)
     }
diff --git a/crates/ra_ide_api/src/db.rs b/crates/ra_ide_api/src/db.rs
index 785e71808b..9146b647a8 100644
--- a/crates/ra_ide_api/src/db.rs
+++ b/crates/ra_ide_api/src/db.rs
@@ -23,7 +23,6 @@ use crate::{
     hir::db::InternDatabaseStorage,
     hir::db::AstDatabaseStorage,
     hir::db::DefDatabaseStorage,
-    hir::db::DefDatabase2Storage,
     hir::db::HirDatabaseStorage
 )]
 #[derive(Debug)]
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 04dca402c1..d88b7ef376 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -229,6 +229,7 @@ fn install_server(opts: ServerOpt) -> Result<()> {
     let mut old_rust = false;
     if let Ok(output) = run_with_output("cargo --version", ".") {
         if let Ok(stdout) = String::from_utf8(output.stdout) {
+            println!("{}", stdout);
             if !check_version(&stdout, REQUIRED_RUST_VERSION) {
                 old_rust = true;
             }


Test patch:
diff --git a/crates/ra_hir/src/nameres/tests/mod_resolution.rs b/crates/ra_hir/src/nameres/tests/mod_resolution.rs
index abfe8b1c34..f569aacdc6 100644
--- a/crates/ra_hir/src/nameres/tests/mod_resolution.rs
+++ b/crates/ra_hir/src/nameres/tests/mod_resolution.rs
@@ -2,7 +2,7 @@ use super::*;
 
 #[test]
 fn name_res_works_for_broken_modules() {
-    // covers!(name_res_works_for_broken_modules);
+    covers!(name_res_works_for_broken_modules);
     let map = def_map(
         "
         //- /lib.rs