Repository: rust-analyzer/rust-analyzer
Pull request #440 (2019-01-05 20:30:37)

Implement type inference for boolean operators
Tried implementing the easiest part of https://github.com/rust-analyzer/rust-analyzer/issues/390. Hope this is somewhat close to what the intent of the issue was. Found it surprisingly easy to find my way around the repository - it's well organized!

Very grateful for any pointers.


Patch:
diff --git a/crates/ra_analysis/src/completion/complete_scope.rs b/crates/ra_analysis/src/completion/complete_scope.rs
index ee9052d3d5..4dead36896 100644
--- a/crates/ra_analysis/src/completion/complete_scope.rs
+++ b/crates/ra_analysis/src/completion/complete_scope.rs
@@ -15,22 +15,19 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) ->
         None => return Ok(()),
     };
     if let Some(function) = &ctx.function {
-        let scopes = function.scopes(ctx.db)?;
+        let scopes = function.scopes(ctx.db);
         complete_fn(acc, &scopes, ctx.offset);
     }
 
     let module_scope = module.scope(ctx.db)?;
-    let (file_id, _) = module.defenition_source(ctx.db)?;
     module_scope
         .entries()
         .filter(|(_name, res)| {
             // Don't expose this item
-            // FIXME: this penetrates through all kinds of abstractions,
-            // we need to figura out the way to do it less ugly.
             match res.import {
                 None => true,
                 Some(import) => {
-                    let range = import.range(ctx.db, file_id);
+                    let range = import.range(ctx.db, module.file_id());
                     !range.is_subrange(&ctx.leaf.range())
                 }
             }
@@ -43,17 +40,20 @@ pub(super) fn complete_scope(acc: &mut Completions, ctx: &CompletionContext) ->
     Ok(())
 }
 
-fn complete_fn(acc: &mut Completions, scopes: &hir::ScopesWithSyntaxMapping, offset: TextUnit) {
+fn complete_fn(acc: &mut Completions, scopes: &hir::FnScopes, offset: TextUnit) {
     let mut shadowed = FxHashSet::default();
     scopes
         .scope_chain_for_offset(offset)
-        .flat_map(|scope| scopes.scopes.entries(scope).iter())
+        .flat_map(|scope| scopes.entries(scope).iter())
         .filter(|entry| shadowed.insert(entry.name()))
         .for_each(|entry| {
             CompletionItem::new(CompletionKind::Reference, entry.name().to_string())
                 .kind(CompletionItemKind::Binding)
                 .add_to(acc)
         });
+    if scopes.self_param.is_some() {
+        CompletionItem::new(CompletionKind::Reference, "self").add_to(acc);
+    }
 }
 
 #[cfg(test)]
diff --git a/crates/ra_analysis/src/db.rs b/crates/ra_analysis/src/db.rs
index 1709be5cf4..5422a400b6 100644
--- a/crates/ra_analysis/src/db.rs
+++ b/crates/ra_analysis/src/db.rs
@@ -106,9 +106,6 @@ salsa::database_storage! {
             fn struct_data() for hir::db::StructDataQuery;
             fn enum_data() for hir::db::EnumDataQuery;
             fn impls_in_module() for hir::db::ImplsInModuleQuery;
-            fn body_hir() for hir::db::BodyHirQuery;
-            fn body_syntax_mapping() for hir::db::BodySyntaxMappingQuery;
-            fn fn_signature() for hir::db::FnSignatureQuery;
         }
     }
 }
diff --git a/crates/ra_analysis/src/goto_defenition.rs b/crates/ra_analysis/src/goto_defenition.rs
index aa0616e3b3..e37421f8dc 100644
--- a/crates/ra_analysis/src/goto_defenition.rs
+++ b/crates/ra_analysis/src/goto_defenition.rs
@@ -28,7 +28,7 @@ pub(crate) fn reference_defenition(
     if let Some(fn_descr) =
         hir::source_binder::function_from_child_node(db, file_id, name_ref.syntax())?
     {
-        let scope = fn_descr.scopes(db)?;
+        let scope = fn_descr.scopes(db);
         // First try to resolve the symbol locally
         if let Some(entry) = scope.resolve_local_name(name_ref) {
             let nav = NavigationTarget {
@@ -60,8 +60,8 @@ fn name_defenition(
             if let Some(child_module) =
                 hir::source_binder::module_from_declaration(db, file_id, module)?
             {
-                let (file_id, _) = child_module.defenition_source(db)?;
-                let name = match child_module.name(db)? {
+                let file_id = child_module.file_id();
+                let name = match child_module.name() {
                     Some(name) => name.to_string().into(),
                     None => "".into(),
                 };
diff --git a/crates/ra_analysis/src/imp.rs b/crates/ra_analysis/src/imp.rs
index 07a9662905..6ab3c5476b 100644
--- a/crates/ra_analysis/src/imp.rs
+++ b/crates/ra_analysis/src/imp.rs
@@ -105,35 +105,39 @@ impl db::RootDatabase {
         &self,
         position: FilePosition,
     ) -> Cancelable<Vec<NavigationTarget>> {
-        let module = match source_binder::module_from_position(self, position)? {
+        let descr = match source_binder::module_from_position(self, position)? {
             None => return Ok(Vec::new()),
             Some(it) => it,
         };
-        let (file_id, ast_module) = match module.declaration_source(self)? {
+        let (file_id, decl) = match descr.parent_link_source(self) {
             None => return Ok(Vec::new()),
             Some(it) => it,
         };
-        let ast_module = ast_module.borrowed();
-        let name = ast_module.name().unwrap();
+        let decl = decl.borrowed();
+        let decl_name = decl.name().unwrap();
         Ok(vec![NavigationTarget {
             file_id,
-            name: name.text(),
-            range: name.syntax().range(),
+            name: decl_name.text(),
+            range: decl_name.syntax().range(),
             kind: MODULE,
             ptr: None,
         }])
     }
     /// Returns `Vec` for the same reason as `parent_module`
     pub(crate) fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
-        let module = match source_binder::module_from_file_id(self, file_id)? {
-            Some(it) => it,
+        let descr = match source_binder::module_from_file_id(self, file_id)? {
             None => return Ok(Vec::new()),
-        };
-        let krate = match module.krate(self)? {
             Some(it) => it,
-            None => return Ok(Vec::new()),
         };
-        Ok(vec![krate.crate_id()])
+        let root = descr.crate_root();
+        let file_id = root.file_id();
+
+        let crate_graph = self.crate_graph();
+        let crate_id = crate_graph.crate_id_for_crate_root(file_id);
+        Ok(crate_id.into_iter().collect())
+    }
+    pub(crate) fn crate_root(&self, crate_id: CrateId) -> FileId {
+        self.crate_graph().crate_root(crate_id)
     }
     pub(crate) fn find_all_refs(
         &self,
@@ -153,7 +157,7 @@ impl db::RootDatabase {
             .collect::<Vec<_>>();
         ret.extend(
             descr
-                .scopes(self)?
+                .scopes(self)
                 .find_all_refs(binding)
                 .into_iter()
                 .map(|ref_desc| (position.file_id, ref_desc.range)),
@@ -181,7 +185,7 @@ impl db::RootDatabase {
                 position.file_id,
                 name_ref.syntax(),
             )?);
-            let scope = descr.scopes(db)?;
+            let scope = descr.scopes(db);
             let resolved = ctry!(scope.resolve_local_name(name_ref));
             let resolved = resolved.ptr().resolve(source_file);
             let binding = ctry!(find_node_at_offset::<ast::BindPat>(
@@ -205,7 +209,7 @@ impl db::RootDatabase {
             })
             .collect::<Vec<_>>();
         if let Some(m) = source_binder::module_from_file_id(self, file_id)? {
-            for (name_node, problem) in m.problems(self)? {
+            for (name_node, problem) in m.problems(self) {
                 let source_root = self.file_source_root(file_id);
                 let diag = match problem {
                     Problem::UnresolvedModule { candidate } => {
diff --git a/crates/ra_analysis/src/lib.rs b/crates/ra_analysis/src/lib.rs
index 77f77e9a8c..390c31c3fa 100644
--- a/crates/ra_analysis/src/lib.rs
+++ b/crates/ra_analysis/src/lib.rs
@@ -397,7 +397,7 @@ impl Analysis {
     }
     /// Returns the root file of the given crate.
     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
-        Ok(self.db.crate_graph().crate_root(crate_id))
+        Ok(self.db.crate_root(crate_id))
     }
     /// Returns the set of possible targets to run for the current file.
     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
diff --git a/crates/ra_analysis/src/runnables.rs b/crates/ra_analysis/src/runnables.rs
index 216209098d..4742676059 100644
--- a/crates/ra_analysis/src/runnables.rs
+++ b/crates/ra_analysis/src/runnables.rs
@@ -72,15 +72,12 @@ fn runnable_mod(db: &RootDatabase, file_id: FileId, module: ast::Module) -> Opti
     let range = module.syntax().range();
     let module =
         hir::source_binder::module_from_child_node(db, file_id, module.syntax()).ok()??;
-
-    // FIXME: thread cancellation instead of `.ok`ing
     let path = module
-        .path_to_root(db)
-        .ok()?
+        .path_to_root()
         .into_iter()
         .rev()
-        .filter_map(|it| it.name(db).ok())
-        .filter_map(|it| it)
+        .into_iter()
+        .filter_map(|it| it.name().map(Clone::clone))
         .join("::");
     Some(Runnable {
         range,
diff --git a/crates/ra_db/src/syntax_ptr.rs b/crates/ra_db/src/syntax_ptr.rs
index 5bfcedf2bb..744cb23523 100644
--- a/crates/ra_db/src/syntax_ptr.rs
+++ b/crates/ra_db/src/syntax_ptr.rs
@@ -1,6 +1,6 @@
 use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, TextRange};
 
-/// A pointer to a syntax node inside a file.
+/// A pionter to a syntax node inside a file.
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub struct LocalSyntaxPtr {
     range: TextRange,
diff --git a/crates/ra_editor/src/assists/split_import.rs b/crates/ra_editor/src/assists/split_import.rs
index e4015f07da..75f9e8dfbb 100644
--- a/crates/ra_editor/src/assists/split_import.rs
+++ b/crates/ra_editor/src/assists/split_import.rs
@@ -19,10 +19,7 @@ pub fn split_import(ctx: AssistCtx) -> Option<Assist> {
     }
 
     let l_curly = colon_colon.range().end();
-    let r_curly = match top_path.syntax().parent().and_then(ast::UseTree::cast) {
-        Some(tree) => tree.syntax().range().end(),
-        None => top_path.syntax().range().end(),
-    };
+    let r_curly = top_path.syntax().range().end();
 
     ctx.build("split import", |edit| {
         edit.insert(l_curly, "{");
@@ -44,13 +41,4 @@ mod tests {
             "use crate::{<|>db::RootDatabase};",
         )
     }
-
-    #[test]
-    fn split_import_works_with_trees() {
-        check_assist(
-            split_import,
-            "use algo:<|>:visitor::{Visitor, visit}",
-            "use algo::{<|>visitor::{Visitor, visit}}",
-        )
-    }
 }
diff --git a/crates/ra_hir/src/code_model_api.rs b/crates/ra_hir/src/code_model_api.rs
deleted file mode 100644
index 09b532f746..0000000000
--- a/crates/ra_hir/src/code_model_api.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-use relative_path::RelativePathBuf;
-use ra_db::{CrateId, Cancelable, FileId};
-use ra_syntax::{ast, SyntaxNode};
-
-use crate::{Name, db::HirDatabase, DefId, Path, PerNs, nameres::ModuleScope};
-
-/// hir::Crate describes a single crate. It's the main inteface with which
-/// crate's dependencies interact. Mostly, it should be just a proxy for the
-/// root module.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct Crate {
-    pub(crate) crate_id: CrateId,
-}
-
-#[derive(Debug)]
-pub struct CrateDependency {
-    pub krate: Crate,
-    pub name: Name,
-}
-
-impl Crate {
-    pub fn crate_id(&self) -> CrateId {
-        self.crate_id
-    }
-    pub fn dependencies(&self, db: &impl HirDatabase) -> Cancelable<Vec<CrateDependency>> {
-        Ok(self.dependencies_impl(db))
-    }
-    pub fn root_module(&self, db: &impl HirDatabase) -> Cancelable<Option<Module>> {
-        self.root_module_impl(db)
-    }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct Module {
-    pub(crate) def_id: DefId,
-}
-
-pub enum ModuleSource {
-    SourceFile(ast::SourceFileNode),
-    Module(ast::ModuleNode),
-}
-
-#[derive(Clone, Debug, Hash, PartialEq, Eq)]
-pub enum Problem {
-    UnresolvedModule {
-        candidate: RelativePathBuf,
-    },
-    NotDirOwner {
-        move_to: RelativePathBuf,
-        candidate: RelativePathBuf,
-    },
-}
-
-impl Module {
-    /// Name of this module.
-    pub fn name(&self, db: &impl HirDatabase) -> Cancelable<Option<Name>> {
-        self.name_impl(db)
-    }
-
-    /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
-    pub fn defenition_source(&self, db: &impl HirDatabase) -> Cancelable<(FileId, ModuleSource)> {
-        self.defenition_source_impl(db)
-    }
-    /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
-    /// `None` for the crate root.
-    pub fn declaration_source(
-        &self,
-        db: &impl HirDatabase,
-    ) -> Cancelable<Option<(FileId, ast::ModuleNode)>> {
-        self.declaration_source_impl(db)
-    }
-
-    /// Returns the crate this module is part of.
-    pub fn krate(&self, db: &impl HirDatabase) -> Cancelable<Option<Crate>> {
-        self.krate_impl(db)
-    }
-    /// Topmost parent of this module. Every module has a `crate_root`, but some
-    /// might miss `krate`. This can happen if a module's file is not included
-    /// into any module tree of any target from Cargo.toml.
-    pub fn crate_root(&self, db: &impl HirDatabase) -> Cancelable<Module> {
-        self.crate_root_impl(db)
-    }
-    /// Finds a child module with the specified name.
-    pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
-        self.child_impl(db, name)
-    }
-    /// Finds a parent module.
-    pub fn parent(&self, db: &impl HirDatabase) -> Cancelable<Option<Module>> {
-        self.parent_impl(db)
-    }
-    pub fn path_to_root(&self, db: &impl HirDatabase) -> Cancelable<Vec<Module>> {
-        let mut res = vec![self.clone()];
-        let mut curr = self.clone();
-        while let Some(next) = curr.parent(db)? {
-            res.push(next.clone());
-            curr = next
-        }
-        Ok(res)
-    }
-    /// Returns a `ModuleScope`: a set of items, visible in this module.
-    pub fn scope(&self, db: &impl HirDatabase) -> Cancelable<ModuleScope> {
-        self.scope_impl(db)
-    }
-    pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> Cancelable<PerNs<DefId>> {
-        self.resolve_path_impl(db, path)
-    }
-    pub fn problems(&self, db: &impl HirDatabase) -> Cancelable<Vec<(SyntaxNode, Problem)>> {
-        self.problems_impl(db)
-    }
-}
diff --git a/crates/ra_hir/src/code_model_impl.rs b/crates/ra_hir/src/code_model_impl.rs
deleted file mode 100644
index 157b0c6168..0000000000
--- a/crates/ra_hir/src/code_model_impl.rs
+++ /dev/null
@@ -1,2 +0,0 @@
-mod krate; // `crate` is invalid ident :(
-mod module;
diff --git a/crates/ra_hir/src/code_model_impl/krate.rs b/crates/ra_hir/src/code_model_impl/krate.rs
deleted file mode 100644
index 3275eafed4..0000000000
--- a/crates/ra_hir/src/code_model_impl/krate.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use ra_db::{CrateId, Cancelable};
-
-use crate::{
-    HirFileId, Crate, CrateDependency, AsName, DefLoc, DefKind, Module, SourceItemId,
-    db::HirDatabase,
-};
-
-impl Crate {
-    pub(crate) fn new(crate_id: CrateId) -> Crate {
-        Crate { crate_id }
-    }
-    pub(crate) fn dependencies_impl(&self, db: &impl HirDatabase) -> Vec<CrateDependency> {
-        let crate_graph = db.crate_graph();
-        crate_graph
-            .dependencies(self.crate_id)
-            .map(|dep| {
-                let krate = Crate::new(dep.crate_id());
-                let name = dep.as_name();
-                CrateDependency { krate, name }
-            })
-            .collect()
-    }
-    pub(crate) fn root_module_impl(&self, db: &impl HirDatabase) -> Cancelable<Option<Module>> {
-        let crate_graph = db.crate_graph();
-        let file_id = crate_graph.crate_root(self.crate_id);
-        let source_root_id = db.file_source_root(file_id);
-        let file_id = HirFileId::from(file_id);
-        let module_tree = db.module_tree(source_root_id)?;
-        // FIXME: teach module tree about crate roots instead of guessing
-        let source = SourceItemId {
-            file_id,
-            item_id: None,
-        };
-        let module_id = ctry!(module_tree.find_module_by_source(source));
-
-        let def_loc = DefLoc {
-            kind: DefKind::Module,
-            source_root_id,
-            module_id,
-            source_item_id: module_id.source(&module_tree),
-        };
-        let def_id = def_loc.id(db);
-
-        let module = Module::new(def_id);
-        Ok(Some(module))
-    }
-}
diff --git a/crates/ra_hir/src/code_model_impl/module.rs b/crates/ra_hir/src/code_model_impl/module.rs
deleted file mode 100644
index eb35779f1c..0000000000
--- a/crates/ra_hir/src/code_model_impl/module.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-use ra_db::{Cancelable, SourceRootId, FileId};
-use ra_syntax::{ast, SyntaxNode, AstNode};
-
-use crate::{
-    Module, ModuleSource, Problem,
-    Crate, DefId, DefLoc, DefKind, Name, Path, PathKind, PerNs, Def, ModuleId,
-    nameres::ModuleScope,
-    db::HirDatabase,
-};
-
-impl Module {
-    pub(crate) fn new(def_id: DefId) -> Self {
-        crate::code_model_api::Module { def_id }
-    }
-    pub(crate) fn from_module_id(
-        db: &impl HirDatabase,
-        source_root_id: SourceRootId,
-        module_id: ModuleId,
-    ) -> Cancelable<Self> {
-        let module_tree = db.module_tree(source_root_id)?;
-        let def_loc = DefLoc {
-            kind: DefKind::Module,
-            source_root_id,
-            module_id,
-            source_item_id: module_id.source(&module_tree),
-        };
-        let def_id = def_loc.id(db);
-        let module = Module::new(def_id);
-        Ok(module)
-    }
-
-    pub(crate) fn name_impl(&self, db: &impl HirDatabase) -> Cancelable<Option<Name>> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        let link = ctry!(loc.module_id.parent_link(&module_tree));
-        Ok(Some(link.name(&module_tree).clone()))
-    }
-
-    pub fn defenition_source_impl(
-        &self,
-        db: &impl HirDatabase,
-    ) -> Cancelable<(FileId, ModuleSource)> {
-        let loc = self.def_id.loc(db);
-        let file_id = loc.source_item_id.file_id.as_original_file();
-        let syntax_node = db.file_item(loc.source_item_id);
-        let syntax_node = syntax_node.borrowed();
-        let module_source = if let Some(source_file) = ast::SourceFile::cast(syntax_node) {
-            ModuleSource::SourceFile(source_file.owned())
-        } else {
-            let module = ast::Module::cast(syntax_node).unwrap();
-            ModuleSource::Module(module.owned())
-        };
-        Ok((file_id, module_source))
-    }
-
-    pub fn declaration_source_impl(
-        &self,
-        db: &impl HirDatabase,
-    ) -> Cancelable<Option<(FileId, ast::ModuleNode)>> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        let link = ctry!(loc.module_id.parent_link(&module_tree));
-        let file_id = link
-            .owner(&module_tree)
-            .source(&module_tree)
-            .file_id
-            .as_original_file();
-        let src = link.source(&module_tree, db);
-        Ok(Some((file_id, src)))
-    }
-
-    pub(crate) fn krate_impl(&self, db: &impl HirDatabase) -> Cancelable<Option<Crate>> {
-        let root = self.crate_root(db)?;
-        let loc = root.def_id.loc(db);
-        let file_id = loc.source_item_id.file_id.as_original_file();
-
-        let crate_graph = db.crate_graph();
-        let crate_id = ctry!(crate_graph.crate_id_for_crate_root(file_id));
-        Ok(Some(Crate::new(crate_id)))
-    }
-
-    pub(crate) fn crate_root_impl(&self, db: &impl HirDatabase) -> Cancelable<Module> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        let module_id = loc.module_id.crate_root(&module_tree);
-        Module::from_module_id(db, loc.source_root_id, module_id)
-    }
-    /// Finds a child module with the specified name.
-    pub fn child_impl(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        let child_id = ctry!(loc.module_id.child(&module_tree, name));
-        Module::from_module_id(db, loc.source_root_id, child_id).map(Some)
-    }
-    pub fn parent_impl(&self, db: &impl HirDatabase) -> Cancelable<Option<Module>> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        let parent_id = ctry!(loc.module_id.parent(&module_tree));
-        Module::from_module_id(db, loc.source_root_id, parent_id).map(Some)
-    }
-    /// Returns a `ModuleScope`: a set of items, visible in this module.
-    pub fn scope_impl(&self, db: &impl HirDatabase) -> Cancelable<ModuleScope> {
-        let loc = self.def_id.loc(db);
-        let item_map = db.item_map(loc.source_root_id)?;
-        let res = item_map.per_module[&loc.module_id].clone();
-        Ok(res)
-    }
-    pub fn resolve_path_impl(
-        &self,
-        db: &impl HirDatabase,
-        path: &Path,
-    ) -> Cancelable<PerNs<DefId>> {
-        let mut curr_per_ns = PerNs::types(
-            match path.kind {
-                PathKind::Crate => self.crate_root(db)?,
-                PathKind::Self_ | PathKind::Plain => self.clone(),
-                PathKind::Super => {
-                    if let Some(p) = self.parent(db)? {
-                        p
-                    } else {
-                        return Ok(PerNs::none());
-                    }
-                }
-            }
-            .def_id,
-        );
-
-        let segments = &path.segments;
-        for name in segments.iter() {
-            let curr = if let Some(r) = curr_per_ns.as_ref().take_types() {
-                r
-            } else {
-                return Ok(PerNs::none());
-            };
-            let module = match curr.resolve(db)? {
-                Def::Module(it) => it,
-                // TODO here would be the place to handle enum variants...
-                _ => return Ok(PerNs::none()),
-            };
-            let scope = module.scope(db)?;
-            curr_per_ns = if let Some(r) = scope.get(&name) {
-                r.def_id
-            } else {
-                return Ok(PerNs::none());
-            };
-        }
-        Ok(curr_per_ns)
-    }
-    pub fn problems_impl(&self, db: &impl HirDatabase) -> Cancelable<Vec<(SyntaxNode, Problem)>> {
-        let loc = self.def_id.loc(db);
-        let module_tree = db.module_tree(loc.source_root_id)?;
-        Ok(loc.module_id.problems(&module_tree, db))
-    }
-}
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs
index 033f9d25f7..58296fc6f3 100644
--- a/crates/ra_hir/src/db.rs
+++ b/crates/ra_hir/src/db.rs
@@ -7,10 +7,10 @@ use crate::{
     DefLoc, DefId, MacroCallLoc, MacroCallId, Name, HirFileId,
     SourceFileItems, SourceItemId,
     query_definitions,
-    FnSignature, FnScopes,
+    FnScopes,
     macros::MacroExpansion,
-    module_tree::{ModuleId, ModuleTree},
-    nameres::{ItemMap, InputModuleItems},
+    module::{ModuleId, ModuleTree, ModuleSource,
+    nameres::{ItemMap, InputModuleItems}},
     ty::{InferenceResult, Ty},
     adt::{StructData, EnumData},
     impl_block::ModuleImplBlocks,
@@ -31,7 +31,7 @@ pub trait HirDatabase: SyntaxDatabase
         use fn crate::macros::expand_macro_invocation;
     }
 
-    fn fn_scopes(def_id: DefId) -> Cancelable<Arc<FnScopes>> {
+    fn fn_scopes(def_id: DefId) -> Arc<FnScopes> {
         type FnScopesQuery;
         use fn query_definitions::fn_scopes;
     }
@@ -71,9 +71,9 @@ pub trait HirDatabase: SyntaxDatabase
         use fn query_definitions::file_item;
     }
 
-    fn submodules(source: SourceItemId) -> Cancelable<Arc<Vec<crate::module_tree::Submodule>>> {
+    fn submodules(source: ModuleSource) -> Cancelable<Arc<Vec<crate::module::imp::Submodule>>> {
         type SubmodulesQuery;
-        use fn crate::module_tree::Submodule::submodules_query;
+        use fn query_definitions::submodules;
     }
 
     fn input_module_items(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<InputModuleItems>> {
@@ -86,28 +86,13 @@ pub trait HirDatabase: SyntaxDatabase
     }
     fn module_tree(source_root_id: SourceRootId) -> Cancelable<Arc<ModuleTree>> {
         type ModuleTreeQuery;
-        use fn crate::module_tree::ModuleTree::module_tree_query;
+        use fn crate::module::imp::module_tree;
     }
 
     fn impls_in_module(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<ModuleImplBlocks>> {
         type ImplsInModuleQuery;
         use fn crate::impl_block::impls_in_module;
     }
-
-    fn body_hir(def_id: DefId) -> Cancelable<Arc<crate::expr::Body>> {
-        type BodyHirQuery;
-        use fn crate::expr::body_hir;
-    }
-
-    fn body_syntax_mapping(def_id: DefId) -> Cancelable<Arc<crate::expr::BodySyntaxMapping>> {
-        type BodySyntaxMappingQuery;
-        use fn crate::expr::body_syntax_mapping;
-    }
-
-    fn fn_signature(def_id: DefId) -> Arc<FnSignature> {
-        type FnSignatureQuery;
-        use fn crate::function::fn_signature;
-    }
 }
 
 }
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs
deleted file mode 100644
index 6866fc2acf..0000000000
--- a/crates/ra_hir/src/expr.rs
+++ /dev/null
@@ -1,745 +0,0 @@
-use std::ops::Index;
-use std::sync::Arc;
-
-use rustc_hash::FxHashMap;
-
-use ra_arena::{Arena, RawId, impl_arena_id};
-use ra_db::{LocalSyntaxPtr, Cancelable};
-use ra_syntax::ast::{self, AstNode, LoopBodyOwner, ArgListOwner, NameOwner};
-
-use crate::{Path, type_ref::{Mutability, TypeRef}, Name, HirDatabase, DefId, Def, name::AsName};
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct ExprId(RawId);
-impl_arena_id!(ExprId);
-
-/// The body of an item (function, const etc.).
-#[derive(Debug, Eq, PartialEq)]
-pub struct Body {
-    exprs: Arena<ExprId, Expr>,
-    pats: Arena<PatId, Pat>,
-    /// The patterns for the function's arguments. While the argument types are
-    /// part of the function signature, the patterns are not (they don't change
-    /// the external type of the function).
-    ///
-    /// If this `Body` is for the body of a constant, this will just be
-    /// empty.
-    args: Vec<PatId>,
-    /// The `ExprId` of the actual body expression.
-    body_expr: ExprId,
-}
-
-/// An item body together with the mapping from syntax nodes to HIR expression
-/// IDs. This is needed to go from e.g. a position in a file to the HIR
-/// expression containing it; but for type inference etc., we want to operate on
-/// a structure that is agnostic to the actual positions of expressions in the
-/// file, so that we don't recompute the type inference whenever some whitespace
-/// is typed.
-#[derive(Debug, Eq, PartialEq)]
-pub struct BodySyntaxMapping {
-    body: Arc<Body>,
-    expr_syntax_mapping: FxHashMap<LocalSyntaxPtr, ExprId>,
-    expr_syntax_mapping_back: FxHashMap<ExprId, LocalSyntaxPtr>,
-    pat_syntax_mapping: FxHashMap<LocalSyntaxPtr, PatId>,
-    pat_syntax_mapping_back: FxHashMap<PatId, LocalSyntaxPtr>,
-}
-
-impl Body {
-    pub fn args(&self) -> &[PatId] {
-        &self.args
-    }
-
-    pub fn body_expr(&self) -> ExprId {
-        self.body_expr
-    }
-}
-
-impl Index<ExprId> for Body {
-    type Output = Expr;
-
-    fn index(&self, expr: ExprId) -> &Expr {
-        &self.exprs[expr]
-    }
-}
-
-impl Index<PatId> for Body {
-    type Output = Pat;
-
-    fn index(&self, pat: PatId) -> &Pat {
-        &self.pats[pat]
-    }
-}
-
-impl BodySyntaxMapping {
-    pub fn expr_syntax(&self, expr: ExprId) -> Option<LocalSyntaxPtr> {
-        self.expr_syntax_mapping_back.get(&expr).cloned()
-    }
-    pub fn syntax_expr(&self, ptr: LocalSyntaxPtr) -> Option<ExprId> {
-        self.expr_syntax_mapping.get(&ptr).cloned()
-    }
-    pub fn pat_syntax(&self, pat: PatId) -> Option<LocalSyntaxPtr> {
-        self.pat_syntax_mapping_back.get(&pat).cloned()
-    }
-    pub fn syntax_pat(&self, ptr: LocalSyntaxPtr) -> Option<PatId> {
-        self.pat_syntax_mapping.get(&ptr).cloned()
-    }
-
-    pub fn body(&self) -> &Arc<Body> {
-        &self.body
-    }
-}
-
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub enum Expr {
-    /// This is produced if syntax tree does not have a required expression piece.
-    Missing,
-    Path(Path),
-    If {
-        condition: ExprId,
-        then_branch: ExprId,
-        else_branch: Option<ExprId>,
-    },
-    Block {
-        statements: Vec<Statement>,
-        tail: Option<ExprId>,
-    },
-    Loop {
-        body: ExprId,
-    },
-    While {
-        condition: ExprId,
-        body: ExprId,
-    },
-    For {
-        iterable: ExprId,
-        pat: PatId,
-        body: ExprId,
-    },
-    Call {
-        callee: ExprId,
-        args: Vec<ExprId>,
-    },
-    MethodCall {
-        receiver: ExprId,
-        method_name: Name,
-        args: Vec<ExprId>,
-    },
-    Match {
-        expr: ExprId,
-        arms: Vec<MatchArm>,
-    },
-    Continue,
-    Break {
-        expr: Option<ExprId>,
-    },
-    Return {
-        expr: Option<ExprId>,
-    },
-    StructLit {
-        path: Option<Path>,
-        fields: Vec<StructLitField>,
-        spread: Option<ExprId>,
-    },
-    Field {
-        expr: ExprId,
-        name: Name,
-    },
-    Try {
-        expr: ExprId,
-    },
-    Cast {
-        expr: ExprId,
-        type_ref: TypeRef,
-    },
-    Ref {
-        expr: ExprId,
-        mutability: Mutability,
-    },
-    UnaryOp {
-        expr: ExprId,
-        op: Option<UnaryOp>,
-    },
-    Lambda {
-        args: Vec<PatId>,
-        arg_types: Vec<Option<TypeRef>>,
-        body: ExprId,
-    },
-}
-
-pub type UnaryOp = ast::PrefixOp;
-
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub struct MatchArm {
-    pub pats: Vec<PatId>,
-    // guard: Option<ExprId>, // TODO
-    pub expr: ExprId,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub struct StructLitField {
-    pub name: Name,
-    pub expr: ExprId,
-}
-
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub enum Statement {
-    Let {
-        pat: PatId,
-        type_ref: Option<TypeRef>,
-        initializer: Option<ExprId>,
-    },
-    Expr(ExprId),
-}
-
-impl Expr {
-    pub fn walk_child_exprs(&self, mut f: impl FnMut(ExprId)) {
-        match self {
-            Expr::Missing => {}
-            Expr::Path(_) => {}
-            Expr::If {
-                condition,
-                then_branch,
-                else_branch,
-            } => {
-                f(*condition);
-                f(*then_branch);
-                if let Some(else_branch) = else_branch {
-                    f(*else_branch);
-                }
-            }
-            Expr::Block { statements, tail } => {
-                for stmt in statements {
-                    match stmt {
-                        Statement::Let { initializer, .. } => {
-                            if let Some(expr) = initializer {
-                                f(*expr);
-                            }
-                        }
-                        Statement::Expr(e) => f(*e),
-                    }
-                }
-                if let Some(expr) = tail {
-                    f(*expr);
-                }
-            }
-            Expr::Loop { body } => f(*body),
-            Expr::While { condition, body } => {
-                f(*condition);
-                f(*body);
-            }
-            Expr::For { iterable, body, .. } => {
-                f(*iterable);
-                f(*body);
-            }
-            Expr::Call { callee, args } => {
-                f(*callee);
-                for arg in args {
-                    f(*arg);
-                }
-            }
-            Expr::MethodCall { receiver, args, .. } => {
-                f(*receiver);
-                for arg in args {
-                    f(*arg);
-                }
-            }
-            Expr::Match { expr, arms } => {
-                f(*expr);
-                for arm in arms {
-                    f(arm.expr);
-                }
-            }
-            Expr::Continue => {}
-            Expr::Break { expr } | Expr::Return { expr } => {
-                if let Some(expr) = expr {
-                    f(*expr);
-                }
-            }
-            Expr::StructLit { fields, spread, .. } => {
-                for field in fields {
-                    f(field.expr);
-                }
-                if let Some(expr) = spread {
-                    f(*expr);
-                }
-            }
-            Expr::Lambda { body, .. } => {
-                f(*body);
-            }
-            Expr::Field { expr, .. }
-            | Expr::Try { expr }
-            | Expr::Cast { expr, .. }
-            | Expr::Ref { expr, .. }
-            | Expr::UnaryOp { expr, .. } => {
-                f(*expr);
-            }
-        }
-    }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct PatId(RawId);
-impl_arena_id!(PatId);
-
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub enum Pat {
-    Missing,
-    Bind {
-        name: Name,
-    },
-    TupleStruct {
-        path: Option<Path>,
-        args: Vec<PatId>,
-    },
-}
-
-impl Pat {
-    pub fn walk_child_pats(&self, f: impl FnMut(PatId)) {
-        match self {
-            Pat::Missing | Pat::Bind { .. } => {}
-            Pat::TupleStruct { args, .. } => {
-                args.iter().map(|pat| *pat).for_each(f);
-            }
-        }
-    }
-}
-
-// Queries
-
-pub(crate) fn body_hir(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<Body>> {
-    Ok(Arc::clone(&body_syntax_mapping(db, def_id)?.body))
-}
-
-struct ExprCollector {
-    exprs: Arena<ExprId, Expr>,
-    pats: Arena<PatId, Pat>,
-    expr_syntax_mapping: FxHashMap<LocalSyntaxPtr, ExprId>,
-    expr_syntax_mapping_back: FxHashMap<ExprId, LocalSyntaxPtr>,
-    pat_syntax_mapping: FxHashMap<LocalSyntaxPtr, PatId>,
-    pat_syntax_mapping_back: FxHashMap<PatId, LocalSyntaxPtr>,
-}
-
-impl ExprCollector {
-    fn new() -> Self {
-        ExprCollector {
-            exprs: Arena::default(),
-            pats: Arena::default(),
-            expr_syntax_mapping: FxHashMap::default(),
-            expr_syntax_mapping_back: FxHashMap::default(),
-            pat_syntax_mapping: FxHashMap::default(),
-            pat_syntax_mapping_back: FxHashMap::default(),
-        }
-    }
-
-    fn alloc_expr(&mut self, expr: Expr, syntax_ptr: LocalSyntaxPtr) -> ExprId {
-        let id = self.exprs.alloc(expr);
-        self.expr_syntax_mapping.insert(syntax_ptr, id);
-        self.expr_syntax_mapping_back.insert(id, syntax_ptr);
-        id
-    }
-
-    fn alloc_pat(&mut self, pat: Pat, syntax_ptr: LocalSyntaxPtr) -> PatId {
-        let id = self.pats.alloc(pat);
-        self.pat_syntax_mapping.insert(syntax_ptr, id);
-        self.pat_syntax_mapping_back.insert(id, syntax_ptr);
-        id
-    }
-
-    fn empty_block(&mut self) -> ExprId {
-        let block = Expr::Block {
-            statements: Vec::new(),
-            tail: None,
-        };
-        self.exprs.alloc(block)
-    }
-
-    fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
-        let syntax_ptr = LocalSyntaxPtr::new(expr.syntax());
-        match expr {
-            ast::Expr::IfExpr(e) => {
-                if let Some(pat) = e.condition().and_then(|c| c.pat()) {
-                    // if let -- desugar to match
-                    let pat = self.collect_pat(pat);
-                    let match_expr =
-                        self.collect_expr_opt(e.condition().expect("checked above").expr());
-                    let then_branch = self.collect_block_opt(e.then_branch());
-                    let else_branch = e
-                        .else_branch()
-                        .map(|e| self.collect_block(e))
-                        .unwrap_or_else(|| self.empty_block());
-                    let placeholder_pat = self.pats.alloc(Pat::Missing);
-                    let arms = vec![
-                        MatchArm {
-                            pats: vec![pat],
-                            expr: then_branch,
-                        },
-                        MatchArm {
-                            pats: vec![placeholder_pat],
-                            expr: else_branch,
-                        },
-                    ];
-                    self.alloc_expr(
-                        Expr::Match {
-                            expr: match_expr,
-                            arms,
-                        },
-                        syntax_ptr,
-                    )
-                } else {
-                    let condition = self.collect_expr_opt(e.condition().and_then(|c| c.expr()));
-                    let then_branch = self.collect_block_opt(e.then_branch());
-                    let else_branch = e.else_branch().map(|e| self.collect_block(e));
-                    self.alloc_expr(
-                        Expr::If {
-                            condition,
-                            then_branch,
-                            else_branch,
-                        },
-                        syntax_ptr,
-                    )
-                }
-            }
-            ast::Expr::BlockExpr(e) => self.collect_block_opt(e.block()),
-            ast::Expr::LoopExpr(e) => {
-                let body = self.collect_block_opt(e.loop_body());
-                self.alloc_expr(Expr::Loop { body }, syntax_ptr)
-            }
-            ast::Expr::WhileExpr(e) => {
-                let condition = if let Some(condition) = e.condition() {
-                    if condition.pat().is_none() {
-                        self.collect_expr_opt(condition.expr())
-                    } else {
-                        // TODO handle while let
-                        return self.alloc_expr(Expr::Missing, syntax_ptr);
-                    }
-                } else {
-                    self.exprs.alloc(Expr::Missing)
-                };
-                let body = self.collect_block_opt(e.loop_body());
-                self.alloc_expr(Expr::While { condition, body }, syntax_ptr)
-            }
-            ast::Expr::ForExpr(e) => {
-                let iterable = self.collect_expr_opt(e.iterable());
-                let pat = self.collect_pat_opt(e.pat());
-                let body = self.collect_block_opt(e.loop_body());
-                self.alloc_expr(
-                    Expr::For {
-                        iterable,
-                        pat,
-                        body,
-                    },
-                    syntax_ptr,
-                )
-            }
-            ast::Expr::CallExpr(e) => {
-                let callee = self.collect_expr_opt(e.expr());
-                let args = if let Some(arg_list) = e.arg_list() {
-                    arg_list.args().map(|e| self.collect_expr(e)).collect()
-                } else {
-                    Vec::new()
-                };
-                self.alloc_expr(Expr::Call { callee, args }, syntax_ptr)
-            }
-            ast::Expr::MethodCallExpr(e) => {
-                let receiver = self.collect_expr_opt(e.expr());
-                let args = if let Some(arg_list) = e.arg_list() {
-                    arg_list.args().map(|e| self.collect_expr(e)).collect()
-                } else {
-                    Vec::new()
-                };
-                let method_name = e
-                    .name_ref()
-                    .map(|nr| nr.as_name())
-                    .unwrap_or_else(Name::missing);
-                self.alloc_expr(
-                    Expr::MethodCall {
-                        receiver,
-                        method_name,
-                        args,
-                    },
-                    syntax_ptr,
-                )
-            }
-            ast::Expr::MatchExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                let arms = if let Some(match_arm_list) = e.match_arm_list() {
-                    match_arm_list
-                        .arms()
-                        .map(|arm| MatchArm {
-                            pats: arm.pats().map(|p| self.collect_pat(p)).collect(),
-                            expr: self.collect_expr_opt(arm.expr()),
-                        })
-                        .collect()
-                } else {
-                    Vec::new()
-                };
-                self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
-            }
-            ast::Expr::PathExpr(e) => {
-                let path = e
-                    .path()
-                    .and_then(Path::from_ast)
-                    .map(Expr::Path)
-                    .unwrap_or(Expr::Missing);
-                self.alloc_expr(path, syntax_ptr)
-            }
-            ast::Expr::ContinueExpr(_e) => {
-                // TODO: labels
-                self.alloc_expr(Expr::Continue, syntax_ptr)
-            }
-            ast::Expr::BreakExpr(e) => {
-                let expr = e.expr().map(|e| self.collect_expr(e));
-                self.alloc_expr(Expr::Break { expr }, syntax_ptr)
-            }
-            ast::Expr::ParenExpr(e) => {
-                let inner = self.collect_expr_opt(e.expr());
-                // make the paren expr point to the inner expression as well
-                self.expr_syntax_mapping.insert(syntax_ptr, inner);
-                inner
-            }
-            ast::Expr::ReturnExpr(e) => {
-                let expr = e.expr().map(|e| self.collect_expr(e));
-                self.alloc_expr(Expr::Return { expr }, syntax_ptr)
-            }
-            ast::Expr::StructLit(e) => {
-                let path = e.path().and_then(Path::from_ast);
-                let fields = if let Some(nfl) = e.named_field_list() {
-                    nfl.fields()
-                        .map(|field| StructLitField {
-                            name: field
-                                .name_ref()
-                                .map(|nr| nr.as_name())
-                                .unwrap_or_else(Name::missing),
-                            expr: if let Some(e) = field.expr() {
-                                self.collect_expr(e)
-                            } else if let Some(nr) = field.name_ref() {
-                                // field shorthand
-                                let id = self.exprs.alloc(Expr::Path(Path::from_name_ref(nr)));
-                                self.expr_syntax_mapping
-                                    .insert(LocalSyntaxPtr::new(nr.syntax()), id);
-                                self.expr_syntax_mapping_back
-                                    .insert(id, LocalSyntaxPtr::new(nr.syntax()));
-                                id
-                            } else {
-                                self.exprs.alloc(Expr::Missing)
-                            },
-                        })
-                        .collect()
-                } else {
-                    Vec::new()
-                };
-                let spread = e.spread().map(|s| self.collect_expr(s));
-                self.alloc_expr(
-                    Expr::StructLit {
-                        path,
-                        fields,
-                        spread,
-                    },
-                    syntax_ptr,
-                )
-            }
-            ast::Expr::FieldExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                let name = e
-                    .name_ref()
-                    .map(|nr| nr.as_name())
-                    .unwrap_or_else(Name::missing);
-                self.alloc_expr(Expr::Field { expr, name }, syntax_ptr)
-            }
-            ast::Expr::TryExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                self.alloc_expr(Expr::Try { expr }, syntax_ptr)
-            }
-            ast::Expr::CastExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                let type_ref = TypeRef::from_ast_opt(e.type_ref());
-                self.alloc_expr(Expr::Cast { expr, type_ref }, syntax_ptr)
-            }
-            ast::Expr::RefExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                let mutability = Mutability::from_mutable(e.is_mut());
-                self.alloc_expr(Expr::Ref { expr, mutability }, syntax_ptr)
-            }
-            ast::Expr::PrefixExpr(e) => {
-                let expr = self.collect_expr_opt(e.expr());
-                let op = e.op();
-                self.alloc_expr(Expr::UnaryOp { expr, op }, syntax_ptr)
-            }
-            ast::Expr::LambdaExpr(e) => {
-                let mut args = Vec::new();
-                let mut arg_types = Vec::new();
-                if let Some(pl) = e.param_list() {
-                    for param in pl.params() {
-                        let pat = self.collect_pat_opt(param.pat());
-                        let type_ref = param.type_ref().map(TypeRef::from_ast);
-                        args.push(pat);
-                        arg_types.push(type_ref);
-                    }
-                }
-                let body = self.collect_expr_opt(e.body());
-                self.alloc_expr(
-                    Expr::Lambda {
-                        args,
-                        arg_types,
-                        body,
-                    },
-                    syntax_ptr,
-                )
-            }
-
-            // TODO implement HIR for these:
-            ast::Expr::Label(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::IndexExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::TupleExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::ArrayExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::BinExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-            ast::Expr::Literal(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
-        }
-    }
-
-    fn collect_expr_opt(&mut self, expr: Option<ast::Expr>) -> ExprId {
-        if let Some(expr) = expr {
-            self.collect_expr(expr)
-        } else {
-            self.exprs.alloc(Expr::Missing)
-        }
-    }
-
-    fn collect_block(&mut self, block: ast::Block) -> ExprId {
-        let statements = block
-            .statements()
-            .map(|s| match s {
-                ast::Stmt::LetStmt(stmt) => {
-                    let pat = self.collect_pat_opt(stmt.pat());
-                    let type_ref = stmt.type_ref().map(TypeRef::from_ast);
-                    let initializer = stmt.initializer().map(|e| self.collect_expr(e));
-                    Statement::Let {
-                        pat,
-                        type_ref,
-                        initializer,
-                    }
-                }
-                ast::Stmt::ExprStmt(stmt) => Statement::Expr(self.collect_expr_opt(stmt.expr())),
-            })
-            .collect();
-        let tail = block.expr().map(|e| self.collect_expr(e));
-        self.alloc_expr(
-            Expr::Block { statements, tail },
-            LocalSyntaxPtr::new(block.syntax()),
-        )
-    }
-
-    fn collect_block_opt(&mut self, block: Option<ast::Block>) -> ExprId {
-        if let Some(block) = block {
-            self.collect_block(block)
-        } else {
-            self.exprs.alloc(Expr::Missing)
-        }
-    }
-
-    fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
-        let syntax_ptr = LocalSyntaxPtr::new(pat.syntax());
-        match pat {
-            ast::Pat::BindPat(bp) => {
-                let name = bp
-                    .name()
-                    .map(|nr| nr.as_name())
-                    .unwrap_or_else(Name::missing);
-                self.alloc_pat(Pat::Bind { name }, syntax_ptr)
-            }
-            ast::Pat::TupleStructPat(p) => {
-                let path = p.path().and_then(Path::from_ast);
-                let args = p.args().map(|p| self.collect_pat(p)).collect();
-                self.alloc_pat(Pat::TupleStruct { path, args }, syntax_ptr)
-            }
-            _ => {
-                // TODO
-                self.alloc_pat(Pat::Missing, syntax_ptr)
-            }
-        }
-    }
-
-    fn collect_pat_opt(&mut self, pat: Option<ast::Pat>) -> PatId {
-        if let Some(pat) = pat {
-            self.collect_pat(pat)
-        } else {
-            self.pats.alloc(Pat::Missing)
-        }
-    }
-
-    fn into_body_syntax_mapping(self, args: Vec<PatId>, body_expr: ExprId) -> BodySyntaxMapping {
-        let body = Body {
-            exprs: self.exprs,
-            pats: self.pats,
-            args,
-            body_expr,
-        };
-        BodySyntaxMapping {
-            body: Arc::new(body),
-            expr_syntax_mapping: self.expr_syntax_mapping,
-            expr_syntax_mapping_back: self.expr_syntax_mapping_back,
-            pat_syntax_mapping: self.pat_syntax_mapping,
-            pat_syntax_mapping_back: self.pat_syntax_mapping_back,
-        }
-    }
-}
-
-pub(crate) fn collect_fn_body_syntax(node: ast::FnDef) -> BodySyntaxMapping {
-    let mut collector = ExprCollector::new();
-
-    let args = if let Some(param_list) = node.param_list() {
-        let mut args = Vec::new();
-
-        if let Some(self_param) = param_list.self_param() {
-            let self_param = LocalSyntaxPtr::new(
-                self_param
-                    .self_kw()
-                    .expect("self param without self keyword")
-                    .syntax(),
-            );
-            let arg = collector.alloc_pat(
-                Pat::Bind {
-                    name: Name::self_param(),
-                },
-                self_param,
-            );
-            args.push(arg);
-        }
-
-        for param in param_list.params() {
-            let pat = if let Some(pat) = param.pat() {
-                pat
-            } else {
-                continue;
-            };
-            args.push(collector.collect_pat(pat));
-        }
-        args
-    } else {
-        Vec::new()
-    };
-
-    let body = collector.collect_block_opt(node.body());
-    collector.into_body_syntax_mapping(args, body)
-}
-
-pub(crate) fn body_syntax_mapping(
-    db: &impl HirDatabase,
-    def_id: DefId,
-) -> Cancelable<Arc<BodySyntaxMapping>> {
-    let def = def_id.resolve(db)?;
-
-    let body_syntax_mapping = match def {
-        Def::Function(f) => {
-            let node = f.syntax(db);
-            let node = node.borrowed();
-
-            collect_fn_body_syntax(node)
-        }
-        // TODO: consts, etc.
-        _ => panic!("Trying to get body for item type without body"),
-    };
-
-    Ok(Arc::new(body_syntax_mapping))
-}
diff --git a/crates/ra_hir/src/function.rs b/crates/ra_hir/src/function.rs
index 4627be071f..75ef308ae4 100644
--- a/crates/ra_hir/src/function.rs
+++ b/crates/ra_hir/src/function.rs
@@ -11,9 +11,9 @@ use ra_syntax::{
     ast::{self, AstNode, DocCommentsOwner, NameOwner},
 };
 
-use crate::{DefId, DefKind, HirDatabase, ty::InferenceResult, Module, Crate, impl_block::ImplBlock, expr::{Body, BodySyntaxMapping}, type_ref::{TypeRef, Mutability}, Name};
+use crate::{DefId, DefKind, HirDatabase, ty::InferenceResult, Module, Crate, impl_block::ImplBlock};
 
-pub use self::scope::{FnScopes, ScopesWithSyntaxMapping};
+pub use self::scope::FnScopes;
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Function {
@@ -36,25 +36,8 @@ impl Function {
         ast::FnDef::cast(syntax.borrowed()).unwrap().owned()
     }
 
-    pub fn body(&self, db: &impl HirDatabase) -> Cancelable<Arc<Body>> {
-        db.body_hir(self.def_id)
-    }
-
-    pub fn body_syntax_mapping(&self, db: &impl HirDatabase) -> Cancelable<Arc<BodySyntaxMapping>> {
-        db.body_syntax_mapping(self.def_id)
-    }
-
-    pub fn scopes(&self, db: &impl HirDatabase) -> Cancelable<ScopesWithSyntaxMapping> {
-        let scopes = db.fn_scopes(self.def_id)?;
-        let syntax_mapping = db.body_syntax_mapping(self.def_id)?;
-        Ok(ScopesWithSyntaxMapping {
-            scopes,
-            syntax_mapping,
-        })
-    }
-
-    pub fn signature(&self, db: &impl HirDatabase) -> Arc<FnSignature> {
-        db.fn_signature(self.def_id)
+    pub fn scopes(&self, db: &impl HirDatabase) -> Arc<FnScopes> {
+        db.fn_scopes(self.def_id)
     }
 
     pub fn signature_info(&self, db: &impl HirDatabase) -> Option<FnSignatureInfo> {
@@ -80,60 +63,6 @@ impl Function {
     }
 }
 
-/// The declared signature of a function.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct FnSignature {
-    args: Vec<TypeRef>,
-    ret_type: TypeRef,
-}
-
-impl FnSignature {
-    pub fn args(&self) -> &[TypeRef] {
-        &self.args
-    }
-
-    pub fn ret_type(&self) -> &TypeRef {
-        &self.ret_type
-    }
-}
-
-pub(crate) fn fn_signature(db: &impl HirDatabase, def_id: DefId) -> Arc<FnSignature> {
-    let func = Function::new(def_id);
-    let syntax = func.syntax(db);
-    let node = syntax.borrowed();
-    let mut args = Vec::new();
-    if let Some(param_list) = node.param_list() {
-        if let Some(self_param) = param_list.self_param() {
-            let self_type = if let Some(type_ref) = self_param.type_ref() {
-                TypeRef::from_ast(type_ref)
-            } else {
-                let self_type = TypeRef::Path(Name::self_type().into());
-                match self_param.flavor() {
-                    ast::SelfParamFlavor::Owned => self_type,
-                    ast::SelfParamFlavor::Ref => {
-                        TypeRef::Reference(Box::new(self_type), Mutability::Shared)
-                    }
-                    ast::SelfParamFlavor::MutRef => {
-                        TypeRef::Reference(Box::new(self_type), Mutability::Mut)
-                    }
-                }
-            };
-            args.push(self_type);
-        }
-        for param in param_list.params() {
-            let type_ref = TypeRef::from_ast_opt(param.type_ref());
-            args.push(type_ref);
-        }
-    }
-    let ret_type = if let Some(type_ref) = node.ret_type().and_then(|rt| rt.type_ref()) {
-        TypeRef::from_ast(type_ref)
-    } else {
-        TypeRef::unit()
-    };
-    let sig = FnSignature { args, ret_type };
-    Arc::new(sig)
-}
-
 #[derive(Debug, Clone)]
 pub struct FnSignatureInfo {
     pub name: String,
diff --git a/crates/ra_hir/src/function/scope.rs b/crates/ra_hir/src/function/scope.rs
index 0a12f0b35b..42bfe4f325 100644
--- a/crates/ra_hir/src/function/scope.rs
+++ b/crates/ra_hir/src/function/scope.rs
@@ -1,16 +1,14 @@
-use std::sync::Arc;
-
 use rustc_hash::{FxHashMap, FxHashSet};
 
 use ra_syntax::{
     AstNode, SyntaxNodeRef, TextUnit, TextRange,
     algo::generate,
-    ast,
+    ast::{self, ArgListOwner, LoopBodyOwner, NameOwner},
 };
 use ra_arena::{Arena, RawId, impl_arena_id};
 use ra_db::LocalSyntaxPtr;
 
-use crate::{Name, AsName, expr::{PatId, ExprId, Pat, Expr, Body, Statement, BodySyntaxMapping}};
+use crate::{Name, AsName};
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
 pub struct ScopeId(RawId);
@@ -18,15 +16,15 @@ impl_arena_id!(ScopeId);
 
 #[derive(Debug, PartialEq, Eq)]
 pub struct FnScopes {
-    body: Arc<Body>,
+    pub self_param: Option<LocalSyntaxPtr>,
     scopes: Arena<ScopeId, ScopeData>,
-    scope_for: FxHashMap<ExprId, ScopeId>,
+    scope_for: FxHashMap<LocalSyntaxPtr, ScopeId>,
 }
 
 #[derive(Debug, PartialEq, Eq)]
 pub struct ScopeEntry {
     name: Name,
-    pat: PatId,
+    ptr: LocalSyntaxPtr,
 }
 
 #[derive(Debug, PartialEq, Eq)]
@@ -36,100 +34,28 @@ pub struct ScopeData {
 }
 
 impl FnScopes {
-    pub(crate) fn new(body: Arc<Body>) -> FnScopes {
+    pub(crate) fn new(fn_def: ast::FnDef) -> FnScopes {
         let mut scopes = FnScopes {
-            body: body.clone(),
+            self_param: fn_def
+                .param_list()
+                .and_then(|it| it.self_param())
+                .map(|it| LocalSyntaxPtr::new(it.syntax())),
             scopes: Arena::default(),
             scope_for: FxHashMap::default(),
         };
         let root = scopes.root_scope();
-        scopes.add_params_bindings(root, body.args());
-        compute_expr_scopes(body.body_expr(), &body, &mut scopes, root);
+        scopes.add_params_bindings(root, fn_def.param_list());
+        if let Some(body) = fn_def.body() {
+            compute_block_scopes(body, &mut scopes, root)
+        }
         scopes
     }
     pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
         &self.scopes[scope].entries
     }
-    pub fn scope_chain_for<'a>(&'a self, expr: ExprId) -> impl Iterator<Item = ScopeId> + 'a {
-        generate(self.scope_for(expr), move |&scope| {
-            self.scopes[scope].parent
-        })
-    }
-
-    pub fn resolve_local_name<'a>(
-        &'a self,
-        context_expr: ExprId,
-        name: Name,
-    ) -> Option<&'a ScopeEntry> {
-        let mut shadowed = FxHashSet::default();
-        let ret = self
-            .scope_chain_for(context_expr)
-            .flat_map(|scope| self.entries(scope).iter())
-            .filter(|entry| shadowed.insert(entry.name()))
-            .find(|entry| entry.name() == &name);
-        ret
-    }
-
-    fn root_scope(&mut self) -> ScopeId {
-        self.scopes.alloc(ScopeData {
-            parent: None,
-            entries: vec![],
-        })
-    }
-    fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
-        self.scopes.alloc(ScopeData {
-            parent: Some(parent),
-            entries: vec![],
-        })
-    }
-    fn add_bindings(&mut self, body: &Body, scope: ScopeId, pat: PatId) {
-        match &body[pat] {
-            Pat::Bind { name } => self.scopes[scope].entries.push(ScopeEntry {
-                name: name.clone(),
-                pat,
-            }),
-            p => p.walk_child_pats(|pat| self.add_bindings(body, scope, pat)),
-        }
-    }
-    fn add_params_bindings(&mut self, scope: ScopeId, params: &[PatId]) {
-        let body = Arc::clone(&self.body);
-        params
-            .into_iter()
-            .for_each(|pat| self.add_bindings(&body, scope, *pat));
-    }
-    fn set_scope(&mut self, node: ExprId, scope: ScopeId) {
-        self.scope_for.insert(node, scope);
-    }
-    fn scope_for(&self, expr: ExprId) -> Option<ScopeId> {
-        self.scope_for.get(&expr).map(|&scope| scope)
-    }
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ScopesWithSyntaxMapping {
-    pub syntax_mapping: Arc<BodySyntaxMapping>,
-    pub scopes: Arc<FnScopes>,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ScopeEntryWithSyntax {
-    name: Name,
-    ptr: LocalSyntaxPtr,
-}
-
-impl ScopeEntryWithSyntax {
-    pub fn name(&self) -> &Name {
-        &self.name
-    }
-    pub fn ptr(&self) -> LocalSyntaxPtr {
-        self.ptr
-    }
-}
-
-impl ScopesWithSyntaxMapping {
     pub fn scope_chain<'a>(&'a self, node: SyntaxNodeRef) -> impl Iterator<Item = ScopeId> + 'a {
         generate(self.scope_for(node), move |&scope| {
-            self.scopes.scopes[scope].parent
+            self.scopes[scope].parent
         })
     }
     pub fn scope_chain_for_offset<'a>(
@@ -137,30 +63,26 @@ impl ScopesWithSyntaxMapping {
         offset: TextUnit,
     ) -> impl Iterator<Item = ScopeId> + 'a {
         let scope = self
-            .scopes
             .scope_for
             .iter()
-            .filter_map(|(id, scope)| Some((self.syntax_mapping.expr_syntax(*id)?, scope)))
-            // find containing scope
+            // find containin scope
             .min_by_key(|(ptr, _scope)| {
                 (
                     !(ptr.range().start() <= offset && offset <= ptr.range().end()),
                     ptr.range().len(),
                 )
             })
-            .map(|(ptr, scope)| self.adjust(ptr, *scope, offset));
+            .map(|(ptr, scope)| self.adjust(*ptr, *scope, offset));
 
-        generate(scope, move |&scope| self.scopes.scopes[scope].parent)
+        generate(scope, move |&scope| self.scopes[scope].parent)
     }
     // XXX: during completion, cursor might be outside of any particular
     // expression. Try to figure out the correct scope...
     fn adjust(&self, ptr: LocalSyntaxPtr, original_scope: ScopeId, offset: TextUnit) -> ScopeId {
         let r = ptr.range();
         let child_scopes = self
-            .scopes
             .scope_for
             .iter()
-            .filter_map(|(id, scope)| Some((self.syntax_mapping.expr_syntax(*id)?, scope)))
             .map(|(ptr, scope)| (ptr.range(), scope))
             .filter(|(range, _)| range.start() <= offset && range.is_subrange(&r) && *range != r);
 
@@ -178,27 +100,22 @@ impl ScopesWithSyntaxMapping {
             .unwrap_or(original_scope)
     }
 
-    pub fn resolve_local_name(&self, name_ref: ast::NameRef) -> Option<ScopeEntryWithSyntax> {
+    pub fn resolve_local_name<'a>(&'a self, name_ref: ast::NameRef) -> Option<&'a ScopeEntry> {
         let mut shadowed = FxHashSet::default();
         let name = name_ref.as_name();
         let ret = self
             .scope_chain(name_ref.syntax())
-            .flat_map(|scope| self.scopes.entries(scope).iter())
+            .flat_map(|scope| self.entries(scope).iter())
             .filter(|entry| shadowed.insert(entry.name()))
             .filter(|entry| entry.name() == &name)
             .nth(0);
-        ret.and_then(|entry| {
-            Some(ScopeEntryWithSyntax {
-                name: entry.name().clone(),
-                ptr: self.syntax_mapping.pat_syntax(entry.pat())?,
-            })
-        })
+        ret
     }
 
     pub fn find_all_refs(&self, pat: ast::BindPat) -> Vec<ReferenceDescriptor> {
         let fn_def = pat.syntax().ancestors().find_map(ast::FnDef::cast).unwrap();
         let name_ptr = LocalSyntaxPtr::new(pat.syntax());
-        fn_def
+        let refs: Vec<_> = fn_def
             .syntax()
             .descendants()
             .filter_map(ast::NameRef::cast)
@@ -210,94 +127,203 @@ impl ScopesWithSyntaxMapping {
                 name: name_ref.syntax().text().to_string(),
                 range: name_ref.syntax().range(),
             })
-            .collect()
+            .collect();
+
+        refs
     }
 
+    fn root_scope(&mut self) -> ScopeId {
+        self.scopes.alloc(ScopeData {
+            parent: None,
+            entries: vec![],
+        })
+    }
+    fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
+        self.scopes.alloc(ScopeData {
+            parent: Some(parent),
+            entries: vec![],
+        })
+    }
+    fn add_bindings(&mut self, scope: ScopeId, pat: ast::Pat) {
+        let entries = pat
+            .syntax()
+            .descendants()
+            .filter_map(ast::BindPat::cast)
+            .filter_map(ScopeEntry::new);
+        self.scopes[scope].entries.extend(entries);
+    }
+    fn add_params_bindings(&mut self, scope: ScopeId, params: Option<ast::ParamList>) {
+        params
+            .into_iter()
+            .flat_map(|it| it.params())
+            .filter_map(|it| it.pat())
+            .for_each(|it| self.add_bindings(scope, it));
+    }
+    fn set_scope(&mut self, node: SyntaxNodeRef, scope: ScopeId) {
+        self.scope_for.insert(LocalSyntaxPtr::new(node), scope);
+    }
     fn scope_for(&self, node: SyntaxNodeRef) -> Option<ScopeId> {
         node.ancestors()
             .map(LocalSyntaxPtr::new)
-            .filter_map(|ptr| self.syntax_mapping.syntax_expr(ptr))
-            .find_map(|it| self.scopes.scope_for(it))
+            .filter_map(|it| self.scope_for.get(&it).map(|&scope| scope))
+            .next()
     }
 }
 
 impl ScopeEntry {
+    fn new(pat: ast::BindPat) -> Option<ScopeEntry> {
+        let name = pat.name()?.as_name();
+        let res = ScopeEntry {
+            name,
+            ptr: LocalSyntaxPtr::new(pat.syntax()),
+        };
+        Some(res)
+    }
     pub fn name(&self) -> &Name {
         &self.name
     }
-    pub fn pat(&self) -> PatId {
-        self.pat
+    pub fn ptr(&self) -> LocalSyntaxPtr {
+        self.ptr
     }
 }
 
-fn compute_block_scopes(
-    statements: &[Statement],
-    tail: Option<ExprId>,
-    body: &Body,
-    scopes: &mut FnScopes,
-    mut scope: ScopeId,
-) {
-    for stmt in statements {
+fn compute_block_scopes(block: ast::Block, scopes: &mut FnScopes, mut scope: ScopeId) {
+    // A hack for completion :(
+    scopes.set_scope(block.syntax(), scope);
+    for stmt in block.statements() {
         match stmt {
-            Statement::Let {
-                pat, initializer, ..
-            } => {
-                if let Some(expr) = initializer {
-                    scopes.set_scope(*expr, scope);
-                    compute_expr_scopes(*expr, body, scopes, scope);
+            ast::Stmt::LetStmt(stmt) => {
+                if let Some(expr) = stmt.initializer() {
+                    scopes.set_scope(expr.syntax(), scope);
+                    compute_expr_scopes(expr, scopes, scope);
                 }
                 scope = scopes.new_scope(scope);
-                scopes.add_bindings(body, scope, *pat);
+                if let Some(pat) = stmt.pat() {
+                    scopes.add_bindings(scope, pat);
+                }
             }
-            Statement::Expr(expr) => {
-                scopes.set_scope(*expr, scope);
-                compute_expr_scopes(*expr, body, scopes, scope);
+            ast::Stmt::ExprStmt(expr_stmt) => {
+                if let Some(expr) = expr_stmt.expr() {
+                    scopes.set_scope(expr.syntax(), scope);
+                    compute_expr_scopes(expr, scopes, scope);
+                }
             }
         }
     }
-    if let Some(expr) = tail {
-        compute_expr_scopes(expr, body, scopes, scope);
+    if let Some(expr) = block.expr() {
+        scopes.set_scope(expr.syntax(), scope);
+        compute_expr_scopes(expr, scopes, scope);
     }
 }
 
-fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut FnScopes, scope: ScopeId) {
-    scopes.set_scope(expr, scope);
-    match &body[expr] {
-        Expr::Block { statements, tail } => {
-            compute_block_scopes(&statements, *tail, body, scopes, scope);
+fn compute_expr_scopes(expr: ast::Expr, scopes: &mut FnScopes, scope: ScopeId) {
+    match expr {
+        ast::Expr::IfExpr(e) => {
+            let cond_scope = e
+                .condition()
+                .and_then(|cond| compute_cond_scopes(cond, scopes, scope));
+            if let Some(block) = e.then_branch() {
+                compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope));
+            }
+            if let Some(block) = e.else_branch() {
+                compute_block_scopes(block, scopes, scope);
+            }
         }
-        Expr::For {
-            iterable,
-            pat,
-            body: body_expr,
-        } => {
-            compute_expr_scopes(*iterable, body, scopes, scope);
-            let scope = scopes.new_scope(scope);
-            scopes.add_bindings(body, scope, *pat);
-            compute_expr_scopes(*body_expr, body, scopes, scope);
+        ast::Expr::BlockExpr(e) => {
+            if let Some(block) = e.block() {
+                compute_block_scopes(block, scopes, scope);
+            }
+        }
+        ast::Expr::LoopExpr(e) => {
+            if let Some(block) = e.loop_body() {
+                compute_block_scopes(block, scopes, scope);
+            }
+        }
+        ast::Expr::WhileExpr(e) => {
+            let cond_scope = e
+                .condition()
+                .and_then(|cond| compute_cond_scopes(cond, scopes, scope));
+            if let Some(block) = e.loop_body() {
+                compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope));
+            }
         }
-        Expr::Lambda {
-            args,
-            body: body_expr,
-            ..
-        } => {
+        ast::Expr::ForExpr(e) => {
+            if let Some(expr) = e.iterable() {
+                compute_expr_scopes(expr, scopes, scope);
+            }
+            let mut scope = scope;
+            if let Some(pat) = e.pat() {
+                scope = scopes.new_scope(scope);
+                scopes.add_bindings(scope, pat);
+            }
+            if let Some(block) = e.loop_body() {
+                compute_block_scopes(block, scopes, scope);
+            }
+        }
+        ast::Expr::LambdaExpr(e) => {
             let scope = scopes.new_scope(scope);
-            scopes.add_params_bindings(scope, &args);
-            compute_expr_scopes(*body_expr, body, scopes, scope);
+            scopes.add_params_bindings(scope, e.param_list());
+            if let Some(body) = e.body() {
+                scopes.set_scope(body.syntax(), scope);
+                compute_expr_scopes(body, scopes, scope);
+            }
         }
-        Expr::Match { expr, arms } => {
-            compute_expr_scopes(*expr, body, scopes, scope);
-            for arm in arms {
+        ast::Expr::CallExpr(e) => {
+            compute_call_scopes(e.expr(), e.arg_list(), scopes, scope);
+        }
+        ast::Expr::MethodCallExpr(e) => {
+            compute_call_scopes(e.expr(), e.arg_list(), scopes, scope);
+        }
+        ast::Expr::MatchExpr(e) => {
+            if let Some(expr) = e.expr() {
+                compute_expr_scopes(expr, scopes, scope);
+            }
+            for arm in e.match_arm_list().into_iter().flat_map(|it| it.arms()) {
                 let scope = scopes.new_scope(scope);
-                for pat in &arm.pats {
-                    scopes.add_bindings(body, scope, *pat);
+                for pat in arm.pats() {
+                    scopes.add_bindings(scope, pat);
+                }
+                if let Some(expr) = arm.expr() {
+                    compute_expr_scopes(expr, scopes, scope);
                 }
-                scopes.set_scope(arm.expr, scope);
-                compute_expr_scopes(arm.expr, body, scopes, scope);
             }
         }
-        e => e.walk_child_exprs(|e| compute_expr_scopes(e, body, scopes, scope)),
+        _ => expr
+            .syntax()
+            .children()
+            .filter_map(ast::Expr::cast)
+            .for_each(|expr| compute_expr_scopes(expr, scopes, scope)),
     };
+
+    fn compute_call_scopes(
+        receiver: Option<ast::Expr>,
+        arg_list: Option<ast::ArgList>,
+        scopes: &mut FnScopes,
+        scope: ScopeId,
+    ) {
+        arg_list
+            .into_iter()
+            .flat_map(|it| it.args())
+            .chain(receiver)
+            .for_each(|expr| compute_expr_scopes(expr, scopes, scope));
+    }
+
+    fn compute_cond_scopes(
+        cond: ast::Condition,
+        scopes: &mut FnScopes,
+        scope: ScopeId,
+    ) -> Option<ScopeId> {
+        if let Some(expr) = cond.expr() {
+            compute_expr_scopes(expr, scopes, scope);
+        }
+        if let Some(pat) = cond.pat() {
+            let s = scopes.new_scope(scope);
+            scopes.add_bindings(s, pat);
+            Some(s)
+        } else {
+            None
+        }
+    }
 }
 
 #[derive(Debug)]
@@ -312,8 +338,6 @@ mod tests {
     use ra_syntax::SourceFileNode;
     use test_utils::{extract_offset, assert_eq_text};
 
-    use crate::expr;
-
     use super::*;
 
     fn do_check(code: &str, expected: &[&str]) {
@@ -329,20 +353,15 @@ mod tests {
         let file = SourceFileNode::parse(&code);
         let marker: ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap();
         let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap();
-        let body_hir = expr::collect_fn_body_syntax(fn_def);
-        let scopes = FnScopes::new(Arc::clone(body_hir.body()));
-        let scopes = ScopesWithSyntaxMapping {
-            scopes: Arc::new(scopes),
-            syntax_mapping: Arc::new(body_hir),
-        };
+        let scopes = FnScopes::new(fn_def);
         let actual = scopes
             .scope_chain(marker.syntax())
-            .flat_map(|scope| scopes.scopes.entries(scope))
+            .flat_map(|scope| scopes.entries(scope))
             .map(|it| it.name().to_string())
             .collect::<Vec<_>>()
             .join("\n");
         let expected = expected.join("\n");
-        assert_eq_text!(&expected, &actual);
+        assert_eq_text!(&actual, &expected);
     }
 
     #[test]
@@ -370,7 +389,7 @@ mod tests {
     }
 
     #[test]
-    fn test_method_call_scope() {
+    fn test_metod_call_scope() {
         do_check(
             r"
             fn quux() {
@@ -426,15 +445,10 @@ mod tests {
         let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap();
         let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap();
 
-        let body_hir = expr::collect_fn_body_syntax(fn_def);
-        let scopes = FnScopes::new(Arc::clone(body_hir.body()));
-        let scopes = ScopesWithSyntaxMapping {
-            scopes: Arc::new(scopes),
-            syntax_mapping: Arc::new(body_hir),
-        };
+        let scopes = FnScopes::new(fn_def);
 
         let local_name_entry = scopes.resolve_local_name(name_ref).unwrap();
-        let local_name = local_name_entry.ptr();
+        let local_name = local_name_entry.ptr().resolve(&file);
         let expected_name =
             find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()).unwrap();
         assert_eq!(local_name.range(), expected_name.syntax().range());
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs
index c7391ee056..4d6378e028 100644
--- a/crates/ra_hir/src/ids.rs
+++ b/crates/ra_hir/src/ids.rs
@@ -2,9 +2,7 @@ use ra_db::{SourceRootId, LocationIntener, Cancelable, FileId};
 use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, SourceFile, AstNode, ast};
 use ra_arena::{Arena, RawId, impl_arena_id};
 
-use crate::{HirDatabase, PerNs, ModuleId, Def, Function, Struct, Enum, ImplBlock, Crate};
-
-use crate::code_model_api::Module;
+use crate::{HirDatabase, PerNs, ModuleId, Module, Def, Function, Struct, Enum, ImplBlock, Crate};
 
 /// hir makes a heavy use of ids: integer (u32) handlers to various things. You
 /// can think of id as a pointer (but without a lifetime) or a file descriptor
@@ -153,7 +151,7 @@ impl DefId {
         let loc = self.loc(db);
         let res = match loc.kind {
             DefKind::Module => {
-                let module = Module::from_module_id(db, loc.source_root_id, loc.module_id)?;
+                let module = Module::new(db, loc.source_root_id, loc.module_id)?;
                 Def::Module(module)
             }
             DefKind::Function => {
@@ -177,12 +175,12 @@ impl DefId {
     /// For a module, returns that module; for any other def, returns the containing module.
     pub fn module(self, db: &impl HirDatabase) -> Cancelable<Module> {
         let loc = self.loc(db);
-        Module::from_module_id(db, loc.source_root_id, loc.module_id)
+        Module::new(db, loc.source_root_id, loc.module_id)
     }
 
     /// Returns the containing crate.
     pub fn krate(&self, db: &impl HirDatabase) -> Cancelable<Option<Crate>> {
-        Ok(self.module(db)?.krate(db)?)
+        Ok(self.module(db)?.krate(db))
     }
 
     /// Returns the containing impl block, if this is an impl item.
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs
index 7ce8d17e66..01afa84c49 100644
--- a/crates/ra_hir/src/impl_block.rs
+++ b/crates/ra_hir/src/impl_block.rs
@@ -7,14 +7,12 @@ use ra_db::{LocationIntener, Cancelable, SourceRootId};
 
 use crate::{
     DefId, DefLoc, DefKind, SourceItemId, SourceFileItems,
-    Function,
+    Module, Function,
     db::HirDatabase,
     type_ref::TypeRef,
-    module_tree::ModuleId,
+    module::{ModuleSourceNode, ModuleId},
 };
 
-use crate::code_model_api::{Module, ModuleSource};
-
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ImplBlock {
     module_impl_blocks: Arc<ModuleImplBlocks>,
@@ -66,7 +64,7 @@ impl ImplData {
     ) -> Self {
         let target_trait = node.target_type().map(TypeRef::from_ast);
         let target_type = TypeRef::from_ast_opt(node.target_type());
-        let module_loc = module.def_id.loc(db);
+        let file_id = module.source().file_id();
         let items = if let Some(item_list) = node.item_list() {
             item_list
                 .impl_items()
@@ -77,14 +75,14 @@ impl ImplData {
                         ast::ImplItem::TypeDef(..) => DefKind::Item,
                     };
                     let item_id = file_items.id_of_unchecked(item_node.syntax());
-                    let source_item_id = SourceItemId {
-                        file_id: module_loc.source_item_id.file_id,
-                        item_id: Some(item_id),
-                    };
                     let def_loc = DefLoc {
                         kind,
-                        source_item_id,
-                        ..module_loc
+                        source_root_id: module.source_root_id,
+                        module_id: module.module_id,
+                        source_item_id: SourceItemId {
+                            file_id,
+                            item_id: Some(item_id),
+                        },
                     };
                     let def_id = def_loc.id(db);
                     match item_node {
@@ -150,13 +148,13 @@ impl ModuleImplBlocks {
     }
 
     fn collect(&mut self, db: &impl HirDatabase, module: Module) -> Cancelable<()> {
-        let (file_id, module_source) = module.defenition_source(db)?;
-        let node = match &module_source {
-            ModuleSource::SourceFile(node) => node.borrowed().syntax(),
-            ModuleSource::Module(node) => node.borrowed().syntax(),
+        let module_source_node = module.source().resolve(db);
+        let node = match &module_source_node {
+            ModuleSourceNode::SourceFile(node) => node.borrowed().syntax(),
+            ModuleSourceNode::Module(node) => node.borrowed().syntax(),
         };
 
-        let source_file_items = db.file_items(file_id.into());
+        let source_file_items = db.file_items(module.source().file_id());
 
         for impl_block_ast in node.children().filter_map(ast::ImplBlock::cast) {
             let impl_block = ImplData::from_ast(db, &source_file_items, &module, impl_block_ast);
@@ -176,7 +174,7 @@ pub(crate) fn impls_in_module(
     module_id: ModuleId,
 ) -> Cancelable<Arc<ModuleImplBlocks>> {
     let mut result = ModuleImplBlocks::new();
-    let module = Module::from_module_id(db, source_root_id, module_id)?;
+    let module = Module::new(db, source_root_id, module_id)?;
     result.collect(db, module)?;
     Ok(Arc::new(result))
 }
diff --git a/crates/ra_hir/src/krate.rs b/crates/ra_hir/src/krate.rs
new file mode 100644
index 0000000000..5194e280b7
--- /dev/null
+++ b/crates/ra_hir/src/krate.rs
@@ -0,0 +1,48 @@
+pub use ra_db::{CrateId, Cancelable};
+
+use crate::{HirDatabase, Module, Name, AsName, HirFileId};
+
+/// hir::Crate describes a single crate. It's the main inteface with which
+/// crate's dependencies interact. Mostly, it should be just a proxy for the
+/// root module.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct Crate {
+    crate_id: CrateId,
+}
+
+#[derive(Debug)]
+pub struct CrateDependency {
+    pub krate: Crate,
+    pub name: Name,
+}
+
+impl Crate {
+    pub(crate) fn new(crate_id: CrateId) -> Crate {
+        Crate { crate_id }
+    }
+    pub fn dependencies(&self, db: &impl HirDatabase) -> Vec<CrateDependency> {
+        let crate_graph = db.crate_graph();
+        crate_graph
+            .dependencies(self.crate_id)
+            .map(|dep| {
+                let krate = Crate::new(dep.crate_id());
+                let name = dep.as_name();
+                CrateDependency { krate, name }
+            })
+            .collect()
+    }
+    pub fn root_module(&self, db: &impl HirDatabase) -> Cancelable<Option<Module>> {
+        let crate_graph = db.crate_graph();
+        let file_id = crate_graph.crate_root(self.crate_id);
+        let source_root_id = db.file_source_root(file_id);
+        let file_id = HirFileId::from(file_id);
+        let module_tree = db.module_tree(source_root_id)?;
+        // FIXME: teach module tree about crate roots instead of guessing
+        let (module_id, _) = ctry!(module_tree
+            .modules_with_sources()
+            .find(|(_, src)| src.file_id() == file_id));
+
+        let module = Module::new(db, source_root_id, module_id)?;
+        Ok(Some(module))
+    }
+}
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index 9f133f1749..2abcec441b 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -24,17 +24,14 @@ pub mod source_binder;
 mod ids;
 mod macros;
 mod name;
-mod module_tree;
-mod nameres;
+// can't use `crate` or `r#crate` here :(
+mod krate;
+mod module;
 mod function;
 mod adt;
 mod type_ref;
 mod ty;
 mod impl_block;
-mod expr;
-
-mod code_model_api;
-mod code_model_impl;
 
 use crate::{
     db::HirDatabase,
@@ -45,11 +42,11 @@ use crate::{
 pub use self::{
     path::{Path, PathKind},
     name::Name,
+    krate::Crate,
     ids::{HirFileId, DefId, DefLoc, MacroCallId, MacroCallLoc},
     macros::{MacroDef, MacroInput, MacroExpansion},
-    module_tree::ModuleId,
-    nameres::{ItemMap, PerNs, Namespace, Resolution},
-    function::{Function, FnSignature, FnScopes, ScopesWithSyntaxMapping},
+    module::{Module, ModuleId, Problem, nameres::{ItemMap, PerNs, Namespace}, ModuleScope, Resolution},
+    function::{Function, FnScopes},
     adt::{Struct, Enum},
     ty::Ty,
     impl_block::{ImplBlock, ImplItem},
@@ -57,11 +54,6 @@ pub use self::{
 
 pub use self::function::FnSignatureInfo;
 
-pub use self::code_model_api::{
-    Crate, CrateDependency,
-    Module, ModuleSource, Problem,
-};
-
 pub enum Def {
     Module(Module),
     Function(Function),
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs
index 8d176662cd..a9db932ff0 100644
--- a/crates/ra_hir/src/mock.rs
+++ b/crates/ra_hir/src/mock.rs
@@ -208,9 +208,6 @@ salsa::database_storage! {
             fn struct_data() for db::StructDataQuery;
             fn enum_data() for db::EnumDataQuery;
             fn impls_in_module() for db::ImplsInModuleQuery;
-            fn body_hir() for db::BodyHirQuery;
-            fn body_syntax_mapping() for db::BodySyntaxMappingQuery;
-            fn fn_signature() for db::FnSignatureQuery;
         }
     }
 }
diff --git a/crates/ra_hir/src/module.rs b/crates/ra_hir/src/module.rs
new file mode 100644
index 0000000000..b9821115ce
--- /dev/null
+++ b/crates/ra_hir/src/module.rs
@@ -0,0 +1,376 @@
+pub(super) mod imp;
+pub(super) mod nameres;
+
+use std::sync::Arc;
+use log;
+
+use ra_syntax::{
+    algo::generate,
+    ast::{self, AstNode, NameOwner},
+    SyntaxNode,
+};
+use ra_arena::{Arena, RawId, impl_arena_id};
+use ra_db::{SourceRootId, FileId, Cancelable};
+use relative_path::RelativePathBuf;
+
+use crate::{
+    Def, DefKind, DefLoc, DefId,
+    Name, Path, PathKind, HirDatabase, SourceItemId, SourceFileItemId, Crate,
+    HirFileId,
+};
+
+pub use self::nameres::{ModuleScope, Resolution, Namespace, PerNs};
+
+/// `Module` is API entry point to get all the information
+/// about a particular module.
+#[derive(Debug, Clone)]
+pub struct Module {
+    tree: Arc<ModuleTree>,
+    pub(crate) source_root_id: SourceRootId,
+    pub(crate) module_id: ModuleId,
+}
+
+impl Module {
+    pub(super) fn new(
+        db: &impl HirDatabase,
+        source_root_id: SourceRootId,
+        module_id: ModuleId,
+    ) -> Cancelable<Module> {
+        let module_tree = db.module_tree(source_root_id)?;
+        let res = Module {
+            tree: module_tree,
+            source_root_id,
+            module_id,
+        };
+        Ok(res)
+    }
+
+    /// Returns `mod foo;` or `mod foo {}` node whihc declared this module.
+    /// Returns `None` for the root module
+    pub fn parent_link_source(&self, db: &impl HirDatabase) -> Option<(FileId, ast::ModuleNode)> {
+        let link = self.module_id.parent_link(&self.tree)?;
+        let file_id = link
+            .owner(&self.tree)
+            .source(&self.tree)
+            .file_id()
+            .as_original_file();
+        let src = link.bind_source(&self.tree, db);
+        Some((file_id, src))
+    }
+
+    pub fn file_id(&self) -> FileId {
+        self.source().file_id().as_original_file()
+    }
+
+    /// Parent module. Returns `None` if this is a root module.
+    pub fn parent(&self) -> Option<Module> {
+        let parent_id = self.module_id.parent(&self.tree)?;
+        Some(Module {
+            module_id: parent_id,
+            ..self.clone()
+        })
+    }
+
+    /// Returns an iterator of all children of this module.
+    pub fn children<'a>(&'a self) -> impl Iterator<Item = (Name, Module)> + 'a {
+        self.module_id
+            .children(&self.tree)
+            .map(move |(name, module_id)| {
+                (
+                    name,
+                    Module {
+                        module_id,
+                        ..self.clone()
+                    },
+                )
+            })
+    }
+
+    /// Returns the crate this module is part of.
+    pub fn krate(&self, db: &impl HirDatabase) -> Option<Crate> {
+        let root_id = self.module_id.crate_root(&self.tree);
+        let file_id = root_id.source(&self.tree).file_id().as_original_file();
+        let crate_graph = db.crate_graph();
+        let crate_id = crate_graph.crate_id_for_crate_root(file_id)?;
+        Some(Crate::new(crate_id))
+    }
+
+    /// Returns the all modules on the way to the root.
+    pub fn path_to_root(&self) -> Vec<Module> {
+        generate(Some(self.clone()), move |it| it.parent()).collect::<Vec<Module>>()
+    }
+
+    /// The root of the tree this module is part of
+    pub fn crate_root(&self) -> Module {
+        let root_id = self.module_id.crate_root(&self.tree);
+        Module {
+            module_id: root_id,
+            ..self.clone()
+        }
+    }
+
+    /// `name` is `None` for the crate's root module
+    pub fn name(&self) -> Option<&Name> {
+        let link = self.module_id.parent_link(&self.tree)?;
+        Some(link.name(&self.tree))
+    }
+
+    pub fn def_id(&self, db: &impl HirDatabase) -> DefId {
+        let def_loc = DefLoc {
+            kind: DefKind::Module,
+            source_root_id: self.source_root_id,
+            module_id: self.module_id,
+            source_item_id: self.module_id.source(&self.tree).0,
+        };
+        def_loc.id(db)
+    }
+
+    /// Finds a child module with the specified name.
+    pub fn child(&self, name: &Name) -> Option<Module> {
+        let child_id = self.module_id.child(&self.tree, name)?;
+        Some(Module {
+            module_id: child_id,
+            ..self.clone()
+        })
+    }
+
+    /// Returns a `ModuleScope`: a set of items, visible in this module.
+    pub fn scope(&self, db: &impl HirDatabase) -> Cancelable<ModuleScope> {
+        let item_map = db.item_map(self.source_root_id)?;
+        let res = item_map.per_module[&self.module_id].clone();
+        Ok(res)
+    }
+
+    pub fn resolve_path(&self, db: &impl HirDatabase, path: &Path) -> Cancelable<PerNs<DefId>> {
+        let mut curr_per_ns = PerNs::types(
+            match path.kind {
+                PathKind::Crate => self.crate_root(),
+                PathKind::Self_ | PathKind::Plain => self.clone(),
+                PathKind::Super => {
+                    if let Some(p) = self.parent() {
+                        p
+                    } else {
+                        return Ok(PerNs::none());
+                    }
+                }
+            }
+            .def_id(db),
+        );
+
+        let segments = &path.segments;
+        for name in segments.iter() {
+            let curr = if let Some(r) = curr_per_ns.as_ref().take(Namespace::Types) {
+                r
+            } else {
+                return Ok(PerNs::none());
+            };
+            let module = match curr.resolve(db)? {
+                Def::Module(it) => it,
+                // TODO here would be the place to handle enum variants...
+                _ => return Ok(PerNs::none()),
+            };
+            let scope = module.scope(db)?;
+            curr_per_ns = if let Some(r) = scope.get(&name) {
+                r.def_id
+            } else {
+                return Ok(PerNs::none());
+            };
+        }
+        Ok(curr_per_ns)
+    }
+
+    pub fn problems(&self, db: &impl HirDatabase) -> Vec<(SyntaxNode, Problem)> {
+        self.module_id.problems(&self.tree, db)
+    }
+
+    pub(crate) fn source(&self) -> ModuleSource {
+        self.module_id.source(&self.tree)
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct ModuleId(RawId);
+impl_arena_id!(ModuleId);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct LinkId(RawId);
+impl_arena_id!(LinkId);
+
+/// Physically, rust source is organized as a set of files, but logically it is
+/// organized as a tree of modules. Usually, a single file corresponds to a
+/// single module, but it is not nessary the case.
+///
+/// Module encapsulate the logic of transitioning from the fuzzy world of files
+/// (which can have multiple parents) to the precise world of modules (which
+/// always have one parent).
+#[derive(Default, Debug, PartialEq, Eq)]
+pub struct ModuleTree {
+    mods: Arena<ModuleId, ModuleData>,
+    links: Arena<LinkId, LinkData>,
+}
+
+impl ModuleTree {
+    pub(crate) fn modules<'a>(&'a self) -> impl Iterator<Item = ModuleId> + 'a {
+        self.mods.iter().map(|(id, _)| id)
+    }
+
+    pub(crate) fn modules_with_sources<'a>(
+        &'a self,
+    ) -> impl Iterator<Item = (ModuleId, ModuleSource)> + 'a {
+        self.mods.iter().map(|(id, m)| (id, m.source))
+    }
+}
+
+/// `ModuleSource` is the syntax tree element that produced this module:
+/// either a file, or an inlinde module.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct ModuleSource(SourceItemId);
+
+/// An owned syntax node for a module. Unlike `ModuleSource`,
+/// this holds onto the AST for the whole file.
+pub(crate) enum ModuleSourceNode {
+    SourceFile(ast::SourceFileNode),
+    Module(ast::ModuleNode),
+}
+
+#[derive(Clone, Debug, Hash, PartialEq, Eq)]
+pub enum Problem {
+    UnresolvedModule {
+        candidate: RelativePathBuf,
+    },
+    NotDirOwner {
+        move_to: RelativePathBuf,
+        candidate: RelativePathBuf,
+    },
+}
+
+impl ModuleId {
+    pub(crate) fn source(self, tree: &ModuleTree) -> ModuleSource {
+        tree.mods[self].source
+    }
+    fn parent_link(self, tree: &ModuleTree) -> Option<LinkId> {
+        tree.mods[self].parent
+    }
+    fn parent(self, tree: &ModuleTree) -> Option<ModuleId> {
+        let link = self.parent_link(tree)?;
+        Some(tree.links[link].owner)
+    }
+    fn crate_root(self, tree: &ModuleTree) -> ModuleId {
+        generate(Some(self), move |it| it.parent(tree))
+            .last()
+            .unwrap()
+    }
+    fn child(self, tree: &ModuleTree, name: &Name) -> Option<ModuleId> {
+        let link = tree.mods[self]
+            .children
+            .iter()
+            .map(|&it| &tree.links[it])
+            .find(|it| it.name == *name)?;
+        Some(*link.points_to.first()?)
+    }
+    fn children<'a>(self, tree: &'a ModuleTree) -> impl Iterator<Item = (Name, ModuleId)> + 'a {
+        tree.mods[self].children.iter().filter_map(move |&it| {
+            let link = &tree.links[it];
+            let module = *link.points_to.first()?;
+            Some((link.name.clone(), module))
+        })
+    }
+    fn problems(self, tree: &ModuleTree, db: &impl HirDatabase) -> Vec<(SyntaxNode, Problem)> {
+        tree.mods[self]
+            .children
+            .iter()
+            .filter_map(|&it| {
+                let p = tree.links[it].problem.clone()?;
+                let s = it.bind_source(tree, db);
+                let s = s.borrowed().name().unwrap().syntax().owned();
+                Some((s, p))
+            })
+            .collect()
+    }
+}
+
+impl LinkId {
+    fn owner(self, tree: &ModuleTree) -> ModuleId {
+        tree.links[self].owner
+    }
+    fn name(self, tree: &ModuleTree) -> &Name {
+        &tree.links[self].name
+    }
+    fn bind_source<'a>(self, tree: &ModuleTree, db: &impl HirDatabase) -> ast::ModuleNode {
+        let owner = self.owner(tree);
+        match owner.source(tree).resolve(db) {
+            ModuleSourceNode::SourceFile(root) => {
+                let ast = imp::modules(root.borrowed())
+                    .find(|(name, _)| name == &tree.links[self].name)
+                    .unwrap()
+                    .1;
+                ast.owned()
+            }
+            ModuleSourceNode::Module(it) => it,
+        }
+    }
+}
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct ModuleData {
+    source: ModuleSource,
+    parent: Option<LinkId>,
+    children: Vec<LinkId>,
+}
+
+impl ModuleSource {
+    // precondition: item_id **must** point to module
+    fn new(file_id: HirFileId, item_id: Option<SourceFileItemId>) -> ModuleSource {
+        let source_item_id = SourceItemId { file_id, item_id };
+        ModuleSource(source_item_id)
+    }
+
+    pub(crate) fn new_file(file_id: HirFileId) -> ModuleSource {
+        ModuleSource::new(file_id, None)
+    }
+
+    pub(crate) fn new_inline(
+        db: &impl HirDatabase,
+        file_id: HirFileId,
+        m: ast::Module,
+    ) -> ModuleSource {
+        assert!(!m.has_semi());
+        let file_items = db.file_items(file_id);
+        let item_id = file_items.id_of(file_id, m.syntax());
+        ModuleSource::new(file_id, Some(item_id))
+    }
+
+    pub(crate) fn file_id(self) -> HirFileId {
+        self.0.file_id
+    }
+
+    pub(crate) fn resolve(self, db: &impl HirDatabase) -> ModuleSourceNode {
+        let syntax_node = db.file_item(self.0);
+        let syntax_node = syntax_node.borrowed();
+        if let Some(file) = ast::SourceFile::cast(syntax_node) {
+            return ModuleSourceNode::SourceFile(file.owned());
+        }
+        let module = ast::Module::cast(syntax_node).unwrap();
+        ModuleSourceNode::Module(module.owned())
+    }
+}
+
+#[derive(Hash, Debug, PartialEq, Eq)]
+struct LinkData {
+    owner: ModuleId,
+    name: Name,
+    points_to: Vec<ModuleId>,
+    problem: Option<Problem>,
+}
+
+impl ModuleTree {
+    fn push_mod(&mut self, data: ModuleData) -> ModuleId {
+        self.mods.alloc(data)
+    }
+    fn push_link(&mut self, data: LinkData) -> LinkId {
+        let owner = data.owner;
+        let id = self.links.alloc(data);
+        self.mods[owner].children.push(id);
+        id
+    }
+}
diff --git a/crates/ra_hir/src/module/imp.rs b/crates/ra_hir/src/module/imp.rs
new file mode 100644
index 0000000000..3849026dbd
--- /dev/null
+++ b/crates/ra_hir/src/module/imp.rs
@@ -0,0 +1,190 @@
+use std::sync::Arc;
+
+use ra_syntax::ast::{self, NameOwner};
+use relative_path::RelativePathBuf;
+use rustc_hash::{FxHashMap, FxHashSet};
+use arrayvec::ArrayVec;
+use ra_db::{SourceRoot, SourceRootId, Cancelable, FileId};
+
+use crate::{
+    HirDatabase, Name, AsName,
+};
+
+use super::{
+    LinkData, LinkId, ModuleData, ModuleId, ModuleSource,
+    ModuleTree, Problem,
+};
+
+#[derive(Clone, Hash, PartialEq, Eq, Debug)]
+pub enum Submodule {
+    Declaration(Name),
+    Definition(Name, ModuleSource),
+}
+
+impl Submodule {
+    fn name(&self) -> &Name {
+        match self {
+            Submodule::Declaration(name) => name,
+            Submodule::Definition(name, _) => name,
+        }
+    }
+}
+
+pub(crate) fn modules<'a>(
+    root: impl ast::ModuleItemOwner<'a>,
+) -> impl Iterator<Item = (Name, ast::Module<'a>)> {
+    root.items()
+        .filter_map(|item| match item {
+            ast::ModuleItem::Module(m) => Some(m),
+            _ => None,
+        })
+        .filter_map(|module| {
+            let name = module.name()?.as_name();
+            Some((name, module))
+        })
+}
+
+pub(crate) fn module_tree(
+    db: &impl HirDatabase,
+    source_root: SourceRootId,
+) -> Cancelable<Arc<ModuleTree>> {
+    db.check_canceled()?;
+    let res = create_module_tree(db, source_root)?;
+    Ok(Arc::new(res))
+}
+
+fn create_module_tree<'a>(
+    db: &impl HirDatabase,
+    source_root: SourceRootId,
+) -> Cancelable<ModuleTree> {
+    let mut tree = ModuleTree::default();
+
+    let mut roots = FxHashMap::default();
+    let mut visited = FxHashSet::default();
+
+    let source_root = db.source_root(source_root);
+    for &file_id in source_root.files.values() {
+        let source = ModuleSource::new_file(file_id.into());
+        if visited.contains(&source) {
+            continue; // TODO: use explicit crate_roots here
+        }
+        assert!(!roots.contains_key(&file_id));
+        let module_id = build_subtree(
+            db,
+            &source_root,
+            &mut tree,
+            &mut visited,
+            &mut roots,
+            None,
+            source,
+        )?;
+        roots.insert(file_id, module_id);
+    }
+    Ok(tree)
+}
+
+fn build_subtree(
+    db: &impl HirDatabase,
+    source_root: &SourceRoot,
+    tree: &mut ModuleTree,
+    visited: &mut FxHashSet<ModuleSource>,
+    roots: &mut FxHashMap<FileId, ModuleId>,
+    parent: Option<LinkId>,
+    source: ModuleSource,
+) -> Cancelable<ModuleId> {
+    visited.insert(source);
+    let id = tree.push_mod(ModuleData {
+        source,
+        parent,
+        children: Vec::new(),
+    });
+    for sub in db.submodules(source)?.iter() {
+        let link = tree.push_link(LinkData {
+            name: sub.name().clone(),
+            owner: id,
+            points_to: Vec::new(),
+            problem: None,
+        });
+
+        let (points_to, problem) = match sub {
+            Submodule::Declaration(name) => {
+                let (points_to, problem) = resolve_submodule(db, source, &name);
+                let points_to = points_to
+                    .into_iter()
+                    .map(|file_id| match roots.remove(&file_id) {
+                        Some(module_id) => {
+                            tree.mods[module_id].parent = Some(link);
+                            Ok(module_id)
+                        }
+                        None => build_subtree(
+                            db,
+                            source_root,
+                            tree,
+                            visited,
+                            roots,
+                            Some(link),
+                            ModuleSource::new_file(file_id.into()),
+                        ),
+                    })
+                    .collect::<Cancelable<Vec<_>>>()?;
+                (points_to, problem)
+            }
+            Submodule::Definition(_name, submodule_source) => {
+                let points_to = build_subtree(
+                    db,
+                    source_root,
+                    tree,
+                    visited,
+                    roots,
+                    Some(link),
+                    *submodule_source,
+                )?;
+                (vec![points_to], None)
+            }
+        };
+
+        tree.links[link].points_to = points_to;
+        tree.links[link].problem = problem;
+    }
+    Ok(id)
+}
+
+fn resolve_submodule(
+    db: &impl HirDatabase,
+    source: ModuleSource,
+    name: &Name,
+) -> (Vec<FileId>, Option<Problem>) {
+    // FIXME: handle submodules of inline modules properly
+    let file_id = source.file_id().original_file(db);
+    let source_root_id = db.file_source_root(file_id);
+    let path = db.file_relative_path(file_id);
+    let root = RelativePathBuf::default();
+    let dir_path = path.parent().unwrap_or(&root);
+    let mod_name = path.file_stem().unwrap_or("unknown");
+    let is_dir_owner = mod_name == "mod" || mod_name == "lib" || mod_name == "main";
+
+    let file_mod = dir_path.join(format!("{}.rs", name));
+    let dir_mod = dir_path.join(format!("{}/mod.rs", name));
+    let file_dir_mod = dir_path.join(format!("{}/{}.rs", mod_name, name));
+    let mut candidates = ArrayVec::<[_; 2]>::new();
+    if is_dir_owner {
+        candidates.push(file_mod.clone());
+        candidates.push(dir_mod);
+    } else {
+        candidates.push(file_dir_mod.clone());
+    };
+    let sr = db.source_root(source_root_id);
+    let points_to = candidates
+        .into_iter()
+        .filter_map(|path| sr.files.get(&path))
+        .map(|&it| it)
+        .collect::<Vec<_>>();
+    let problem = if points_to.is_empty() {
+        Some(Problem::UnresolvedModule {
+            candidate: if is_dir_owner { file_mod } else { file_dir_mod },
+        })
+    } else {
+        None
+    };
+    (points_to, problem)
+}
diff --git a/crates/ra_hir/src/nameres.rs b/crates/ra_hir/src/module/nameres.rs
similarity index 97%
rename from crates/ra_hir/src/nameres.rs
rename to crates/ra_hir/src/module/nameres.rs
index 9a412bc82b..3c6851a0a3 100644
--- a/crates/ra_hir/src/nameres.rs
+++ b/crates/ra_hir/src/module/nameres.rs
@@ -31,7 +31,7 @@ use crate::{
     Path, PathKind,
     HirDatabase, Crate,
     Name, AsName,
-    module_tree::{ModuleId, ModuleTree},
+    module::{Module, ModuleId, ModuleTree},
 };
 
 /// Item map is the result of the name resolution. Item map contains, for each
@@ -177,11 +177,11 @@ impl<T> PerNs<T> {
     }
 
     pub fn take_types(self) -> Option<T> {
-        self.take(Namespace::Types)
+        self.types
     }
 
     pub fn take_values(self) -> Option<T> {
-        self.take(Namespace::Values)
+        self.values
     }
 
     pub fn get(&self, namespace: Namespace) -> Option<&T> {
@@ -339,14 +339,14 @@ where
         // Populate extern crates prelude
         {
             let root_id = module_id.crate_root(&self.module_tree);
-            let file_id = root_id.source(&self.module_tree).file_id;
+            let file_id = root_id.source(&self.module_tree).file_id();
             let crate_graph = self.db.crate_graph();
             if let Some(crate_id) = crate_graph.crate_id_for_crate_root(file_id.as_original_file())
             {
                 let krate = Crate::new(crate_id);
-                for dep in krate.dependencies(self.db)? {
+                for dep in krate.dependencies(self.db) {
                     if let Some(module) = dep.krate.root_module(self.db)? {
-                        let def_id = module.def_id;
+                        let def_id = module.def_id(self.db);
                         self.add_module_item(
                             &mut module_items,
                             dep.name.clone(),
@@ -399,7 +399,7 @@ where
                 kind: DefKind::Module,
                 source_root_id: self.source_root,
                 module_id,
-                source_item_id: module_id.source(&self.module_tree),
+                source_item_id: module_id.source(&self.module_tree).0,
             };
             let def_id = def_loc.id(self.db);
             self.add_module_item(&mut module_items, name, PerNs::types(def_id));
@@ -466,7 +466,7 @@ where
                         if source_root_id == self.source_root {
                             target_module_id
                         } else {
-                            let module = crate::code_model_api::Module::new(type_def_id);
+                            let module = Module::new(self.db, source_root_id, target_module_id)?;
                             let path = Path {
                                 segments: import.path.segments[i + 1..].iter().cloned().collect(),
                                 kind: PathKind::Crate,
diff --git a/crates/ra_hir/src/module_tree.rs b/crates/ra_hir/src/module_tree.rs
deleted file mode 100644
index c7a442319c..0000000000
--- a/crates/ra_hir/src/module_tree.rs
+++ /dev/null
@@ -1,368 +0,0 @@
-use std::sync::Arc;
-
-use rustc_hash::{FxHashMap, FxHashSet};
-use arrayvec::ArrayVec;
-use relative_path::RelativePathBuf;
-use ra_db::{FileId, SourceRootId, Cancelable, SourceRoot};
-use ra_syntax::{
-    algo::generate,
-    ast::{self, AstNode, NameOwner},
-    SyntaxNode,
-};
-use ra_arena::{Arena, RawId, impl_arena_id};
-
-use crate::{Name, AsName, HirDatabase, SourceItemId, HirFileId, Problem, SourceFileItems, ModuleSource};
-
-impl ModuleSource {
-    pub fn from_source_item_id(
-        db: &impl HirDatabase,
-        source_item_id: SourceItemId,
-    ) -> ModuleSource {
-        let module_syntax = db.file_item(source_item_id);
-        let module_syntax = module_syntax.borrowed();
-        if let Some(source_file) = ast::SourceFile::cast(module_syntax) {
-            ModuleSource::SourceFile(source_file.owned())
-        } else if let Some(module) = ast::Module::cast(module_syntax) {
-            assert!(module.item_list().is_some(), "expected inline module");
-            ModuleSource::Module(module.owned())
-        } else {
-            panic!("expected file or inline module")
-        }
-    }
-}
-
-#[derive(Clone, Hash, PartialEq, Eq, Debug)]
-pub struct Submodule {
-    name: Name,
-    is_declaration: bool,
-    source: SourceItemId,
-}
-
-impl Submodule {
-    pub(crate) fn submodules_query(
-        db: &impl HirDatabase,
-        source: SourceItemId,
-    ) -> Cancelable<Arc<Vec<Submodule>>> {
-        db.check_canceled()?;
-        let file_id = source.file_id;
-        let file_items = db.file_items(file_id);
-        let module_source = ModuleSource::from_source_item_id(db, source);
-        let submodules = match module_source {
-            ModuleSource::SourceFile(source_file) => {
-                collect_submodules(file_id, &file_items, source_file.borrowed())
-            }
-            ModuleSource::Module(module) => {
-                let module = module.borrowed();
-                collect_submodules(file_id, &file_items, module.item_list().unwrap())
-            }
-        };
-        return Ok(Arc::new(submodules));
-
-        fn collect_submodules<'a>(
-            file_id: HirFileId,
-            file_items: &SourceFileItems,
-            root: impl ast::ModuleItemOwner<'a>,
-        ) -> Vec<Submodule> {
-            modules(root)
-                .map(|(name, m)| Submodule {
-                    name,
-                    is_declaration: m.has_semi(),
-                    source: SourceItemId {
-                        file_id,
-                        item_id: Some(file_items.id_of(file_id, m.syntax())),
-                    },
-                })
-                .collect()
-        }
-    }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct ModuleId(RawId);
-impl_arena_id!(ModuleId);
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct LinkId(RawId);
-impl_arena_id!(LinkId);
-
-/// Physically, rust source is organized as a set of files, but logically it is
-/// organized as a tree of modules. Usually, a single file corresponds to a
-/// single module, but it is not nessary the case.
-///
-/// Module encapsulate the logic of transitioning from the fuzzy world of files
-/// (which can have multiple parents) to the precise world of modules (which
-/// always have one parent).
-#[derive(Default, Debug, PartialEq, Eq)]
-pub struct ModuleTree {
-    mods: Arena<ModuleId, ModuleData>,
-    links: Arena<LinkId, LinkData>,
-}
-
-#[derive(Debug, PartialEq, Eq, Hash)]
-pub struct ModuleData {
-    source: SourceItemId,
-    parent: Option<LinkId>,
-    children: Vec<LinkId>,
-}
-
-#[derive(Hash, Debug, PartialEq, Eq)]
-struct LinkData {
-    source: SourceItemId,
-    owner: ModuleId,
-    name: Name,
-    points_to: Vec<ModuleId>,
-    problem: Option<Problem>,
-}
-
-impl ModuleTree {
-    pub(crate) fn module_tree_query(
-        db: &impl HirDatabase,
-        source_root: SourceRootId,
-    ) -> Cancelable<Arc<ModuleTree>> {
-        db.check_canceled()?;
-        let res = create_module_tree(db, source_root)?;
-        Ok(Arc::new(res))
-    }
-
-    pub(crate) fn modules<'a>(&'a self) -> impl Iterator<Item = ModuleId> + 'a {
-        self.mods.iter().map(|(id, _)| id)
-    }
-
-    pub(crate) fn find_module_by_source(&self, source: SourceItemId) -> Option<ModuleId> {
-        let (res, _) = self.mods.iter().find(|(_, m)| m.source == source)?;
-        Some(res)
-    }
-}
-
-impl ModuleId {
-    pub(crate) fn source(self, tree: &ModuleTree) -> SourceItemId {
-        tree.mods[self].source
-    }
-    pub(crate) fn parent_link(self, tree: &ModuleTree) -> Option<LinkId> {
-        tree.mods[self].parent
-    }
-    pub(crate) fn parent(self, tree: &ModuleTree) -> Option<ModuleId> {
-        let link = self.parent_link(tree)?;
-        Some(tree.links[link].owner)
-    }
-    pub(crate) fn crate_root(self, tree: &ModuleTree) -> ModuleId {
-        generate(Some(self), move |it| it.parent(tree))
-            .last()
-            .unwrap()
-    }
-    pub(crate) fn child(self, tree: &ModuleTree, name: &Name) -> Option<ModuleId> {
-        let link = tree.mods[self]
-            .children
-            .iter()
-            .map(|&it| &tree.links[it])
-            .find(|it| it.name == *name)?;
-        Some(*link.points_to.first()?)
-    }
-    pub(crate) fn children<'a>(
-        self,
-        tree: &'a ModuleTree,
-    ) -> impl Iterator<Item = (Name, ModuleId)> + 'a {
-        tree.mods[self].children.iter().filter_map(move |&it| {
-            let link = &tree.links[it];
-            let module = *link.points_to.first()?;
-            Some((link.name.clone(), module))
-        })
-    }
-    pub(crate) fn problems(
-        self,
-        tree: &ModuleTree,
-        db: &impl HirDatabase,
-    ) -> Vec<(SyntaxNode, Problem)> {
-        tree.mods[self]
-            .children
-            .iter()
-            .filter_map(|&link| {
-                let p = tree.links[link].problem.clone()?;
-                let s = link.source(tree, db);
-                let s = s.borrowed().name().unwrap().syntax().owned();
-                Some((s, p))
-            })
-            .collect()
-    }
-}
-
-impl LinkId {
-    pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId {
-        tree.links[self].owner
-    }
-    pub(crate) fn name(self, tree: &ModuleTree) -> &Name {
-        &tree.links[self].name
-    }
-    pub(crate) fn source(self, tree: &ModuleTree, db: &impl HirDatabase) -> ast::ModuleNode {
-        let syntax_node = db.file_item(tree.links[self].source);
-        ast::ModuleNode::cast(syntax_node.borrowed())
-            .unwrap()
-            .owned()
-    }
-}
-
-impl ModuleTree {
-    fn push_mod(&mut self, data: ModuleData) -> ModuleId {
-        self.mods.alloc(data)
-    }
-    fn push_link(&mut self, data: LinkData) -> LinkId {
-        let owner = data.owner;
-        let id = self.links.alloc(data);
-        self.mods[owner].children.push(id);
-        id
-    }
-}
-
-fn modules<'a>(
-    root: impl ast::ModuleItemOwner<'a>,
-) -> impl Iterator<Item = (Name, ast::Module<'a>)> {
-    root.items()
-        .filter_map(|item| match item {
-            ast::ModuleItem::Module(m) => Some(m),
-            _ => None,
-        })
-        .filter_map(|module| {
-            let name = module.name()?.as_name();
-            Some((name, module))
-        })
-}
-
-fn create_module_tree<'a>(
-    db: &impl HirDatabase,
-    source_root: SourceRootId,
-) -> Cancelable<ModuleTree> {
-    let mut tree = ModuleTree::default();
-
-    let mut roots = FxHashMap::default();
-    let mut visited = FxHashSet::default();
-
-    let source_root = db.source_root(source_root);
-    for &file_id in source_root.files.values() {
-        let source = SourceItemId {
-            file_id: file_id.into(),
-            item_id: None,
-        };
-        if visited.contains(&source) {
-            continue; // TODO: use explicit crate_roots here
-        }
-        assert!(!roots.contains_key(&file_id));
-        let module_id = build_subtree(
-            db,
-            &source_root,
-            &mut tree,
-            &mut visited,
-            &mut roots,
-            None,
-            source,
-        )?;
-        roots.insert(file_id, module_id);
-    }
-    Ok(tree)
-}
-
-fn build_subtree(
-    db: &impl HirDatabase,
-    source_root: &SourceRoot,
-    tree: &mut ModuleTree,
-    visited: &mut FxHashSet<SourceItemId>,
-    roots: &mut FxHashMap<FileId, ModuleId>,
-    parent: Option<LinkId>,
-    source: SourceItemId,
-) -> Cancelable<ModuleId> {
-    visited.insert(source);
-    let id = tree.push_mod(ModuleData {
-        source,
-        parent,
-        children: Vec::new(),
-    });
-    for sub in db.submodules(source)?.iter() {
-        let link = tree.push_link(LinkData {
-            source: sub.source,
-            name: sub.name.clone(),
-            owner: id,
-            points_to: Vec::new(),
-            problem: None,
-        });
-
-        let (points_to, problem) = if sub.is_declaration {
-            let (points_to, problem) = resolve_submodule(db, source.file_id, &sub.name);
-            let points_to = points_to
-                .into_iter()
-                .map(|file_id| match roots.remove(&file_id) {
-                    Some(module_id) => {
-                        tree.mods[module_id].parent = Some(link);
-                        Ok(module_id)
-                    }
-                    None => build_subtree(
-                        db,
-                        source_root,
-                        tree,
-                        visited,
-                        roots,
-                        Some(link),
-                        SourceItemId {
-                            file_id: file_id.into(),
-                            item_id: None,
-                        },
-                    ),
-                })
-                .collect::<Cancelable<Vec<_>>>()?;
-            (points_to, problem)
-        } else {
-            let points_to = build_subtree(
-                db,
-                source_root,
-                tree,
-                visited,
-                roots,
-                Some(link),
-                sub.source,
-            )?;
-            (vec![points_to], None)
-        };
-
-        tree.links[link].points_to = points_to;
-        tree.links[link].problem = problem;
-    }
-    Ok(id)
-}
-
-fn resolve_submodule(
-    db: &impl HirDatabase,
-    file_id: HirFileId,
-    name: &Name,
-) -> (Vec<FileId>, Option<Problem>) {
-    // FIXME: handle submodules of inline modules properly
-    let file_id = file_id.original_file(db);
-    let source_root_id = db.file_source_root(file_id);
-    let path = db.file_relative_path(file_id);
-    let root = RelativePathBuf::default();
-    let dir_path = path.parent().unwrap_or(&root);
-    let mod_name = path.file_stem().unwrap_or("unknown");
-    let is_dir_owner = mod_name == "mod" || mod_name == "lib" || mod_name == "main";
-
-    let file_mod = dir_path.join(format!("{}.rs", name));
-    let dir_mod = dir_path.join(format!("{}/mod.rs", name));
-    let file_dir_mod = dir_path.join(format!("{}/{}.rs", mod_name, name));
-    let mut candidates = ArrayVec::<[_; 2]>::new();
-    if is_dir_owner {
-        candidates.push(file_mod.clone());
-        candidates.push(dir_mod);
-    } else {
-        candidates.push(file_dir_mod.clone());
-    };
-    let sr = db.source_root(source_root_id);
-    let points_to = candidates
-        .into_iter()
-        .filter_map(|path| sr.files.get(&path))
-        .map(|&it| it)
-        .collect::<Vec<_>>();
-    let problem = if points_to.is_empty() {
-        Some(Problem::UnresolvedModule {
-            candidate: if is_dir_owner { file_mod } else { file_dir_mod },
-        })
-    } else {
-        None
-    };
-    (points_to, problem)
-}
diff --git a/crates/ra_hir/src/name.rs b/crates/ra_hir/src/name.rs
index 90229bc540..017caf442e 100644
--- a/crates/ra_hir/src/name.rs
+++ b/crates/ra_hir/src/name.rs
@@ -31,14 +31,6 @@ impl Name {
         Name::new("[missing name]".into())
     }
 
-    pub(crate) fn self_param() -> Name {
-        Name::new("self".into())
-    }
-
-    pub(crate) fn self_type() -> Name {
-        Name::new("Self".into())
-    }
-
     pub(crate) fn tuple_field_name(idx: usize) -> Name {
         Name::new(idx.to_string().into())
     }
@@ -59,8 +51,7 @@ impl Name {
             "u128" => KnownName::U128,
             "f32" => KnownName::F32,
             "f64" => KnownName::F64,
-            "Self" => KnownName::SelfType,
-            "self" => KnownName::SelfParam,
+            "Self" => KnownName::Self_,
             _ => return None,
         };
         Some(name)
@@ -113,6 +104,5 @@ pub(crate) enum KnownName {
     F32,
     F64,
 
-    SelfType,
-    SelfParam,
+    Self_,
 }
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs
index dcf4cf8b65..9fdfa0d131 100644
--- a/crates/ra_hir/src/path.rs
+++ b/crates/ra_hir/src/path.rs
@@ -65,11 +65,6 @@ impl Path {
         }
     }
 
-    /// Converts an `ast::NameRef` into a single-identifier `Path`.
-    pub fn from_name_ref(name_ref: ast::NameRef) -> Path {
-        name_ref.as_name().into()
-    }
-
     /// `true` is this path is a single identifier, like `foo`
     pub fn is_ident(&self) -> bool {
         self.kind == PathKind::Plain && self.segments.len() == 1
@@ -89,15 +84,6 @@ impl Path {
     }
 }
 
-impl From<Name> for Path {
-    fn from(name: Name) -> Path {
-        Path {
-            kind: PathKind::Plain,
-            segments: vec![name],
-        }
-    }
-}
-
 fn expand_use_tree(
     prefix: Option<Path>,
     tree: ast::UseTree,
diff --git a/crates/ra_hir/src/query_definitions.rs b/crates/ra_hir/src/query_definitions.rs
index 8f2c406696..a5d99bedae 100644
--- a/crates/ra_hir/src/query_definitions.rs
+++ b/crates/ra_hir/src/query_definitions.rs
@@ -6,24 +6,28 @@ use std::{
 use rustc_hash::FxHashMap;
 use ra_syntax::{
     AstNode, SyntaxNode,
-    ast::{self, ModuleItemOwner}
+    ast::{self, NameOwner, ModuleItemOwner}
 };
 use ra_db::{SourceRootId, Cancelable,};
 
 use crate::{
-    SourceFileItems, SourceItemId, DefKind, DefId, HirFileId, ModuleSource,
+    SourceFileItems, SourceItemId, DefKind, Function, DefId, Name, AsName, HirFileId,
     MacroCallLoc,
     db::HirDatabase,
     function::FnScopes,
-    module_tree::ModuleId,
-    nameres::{InputModuleItems, ItemMap, Resolver},
+    module::{
+        ModuleSource, ModuleSourceNode, ModuleId,
+        imp::Submodule,
+        nameres::{InputModuleItems, ItemMap, Resolver},
+    },
     adt::{StructData, EnumData},
 };
 
-pub(super) fn fn_scopes(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<FnScopes>> {
-    let body = db.body_hir(def_id)?;
-    let res = FnScopes::new(body);
-    Ok(Arc::new(res))
+pub(super) fn fn_scopes(db: &impl HirDatabase, def_id: DefId) -> Arc<FnScopes> {
+    let function = Function::new(def_id);
+    let syntax = function.syntax(db);
+    let res = FnScopes::new(syntax.borrowed());
+    Arc::new(res)
 }
 
 pub(super) fn struct_data(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<StructData>> {
@@ -58,6 +62,54 @@ pub(super) fn file_item(db: &impl HirDatabase, source_item_id: SourceItemId) ->
     }
 }
 
+pub(crate) fn submodules(
+    db: &impl HirDatabase,
+    source: ModuleSource,
+) -> Cancelable<Arc<Vec<Submodule>>> {
+    db.check_canceled()?;
+    let file_id = source.file_id();
+    let submodules = match source.resolve(db) {
+        ModuleSourceNode::SourceFile(it) => collect_submodules(db, file_id, it.borrowed()),
+        ModuleSourceNode::Module(it) => it
+            .borrowed()
+            .item_list()
+            .map(|it| collect_submodules(db, file_id, it))
+            .unwrap_or_else(Vec::new),
+    };
+    return Ok(Arc::new(submodules));
+
+    fn collect_submodules<'a>(
+        db: &impl HirDatabase,
+        file_id: HirFileId,
+        root: impl ast::ModuleItemOwner<'a>,
+    ) -> Vec<Submodule> {
+        modules(root)
+            .map(|(name, m)| {
+                if m.has_semi() {
+                    Submodule::Declaration(name)
+                } else {
+                    let src = ModuleSource::new_inline(db, file_id, m);
+                    Submodule::Definition(name, src)
+                }
+            })
+            .collect()
+    }
+}
+
+pub(crate) fn modules<'a>(
+    root: impl ast::ModuleItemOwner<'a>,
+) -> impl Iterator<Item = (Name, ast::Module<'a>)> {
+    root.items()
+        .filter_map(|item| match item {
+            ast::ModuleItem::Module(m) => Some(m),
+            _ => None,
+        })
+        .filter_map(|module| {
+            let name = module.name()?.as_name();
+            Some((name, module))
+        })
+}
+
 pub(super) fn input_module_items(
     db: &impl HirDatabase,
     source_root_id: SourceRootId,
@@ -65,8 +117,7 @@ pub(super) fn input_module_items(
 ) -> Cancelable<Arc<InputModuleItems>> {
     let module_tree = db.module_tree(source_root_id)?;
     let source = module_id.source(&module_tree);
-    let file_id = source.file_id;
-    let source = ModuleSource::from_source_item_id(db, source);
+    let file_id = source.file_id();
     let file_items = db.file_items(file_id);
     let fill = |acc: &mut InputModuleItems, items: &mut Iterator<Item = ast::ItemOrMacro>| {
         for item in items {
@@ -97,9 +148,9 @@ pub(super) fn input_module_items(
     };
 
     let mut res = InputModuleItems::default();
-    match source {
-        ModuleSource::SourceFile(it) => fill(&mut res, &mut it.borrowed().items_with_macros()),
-        ModuleSource::Module(it) => {
+    match source.resolve(db) {
+        ModuleSourceNode::SourceFile(it) => fill(&mut res, &mut it.borrowed().items_with_macros()),
+        ModuleSourceNode::Module(it) => {
             if let Some(item_list) = it.borrowed().item_list() {
                 fill(&mut res, &mut item_list.items_with_macros())
             }
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 4c14650c09..85bd844696 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -13,16 +13,14 @@ use ra_syntax::{
 };
 
 use crate::{
-    HirDatabase, Function, SourceItemId,
-    DefKind, DefLoc, AsName, Module,
+    HirDatabase, Module, Function, SourceItemId,
+    module::ModuleSource,
+    DefKind, DefLoc, AsName,
 };
 
 /// Locates the module by `FileId`. Picks topmost module in the file.
 pub fn module_from_file_id(db: &impl HirDatabase, file_id: FileId) -> Cancelable<Option<Module>> {
-    let module_source = SourceItemId {
-        file_id: file_id.into(),
-        item_id: None,
-    };
+    let module_source = ModuleSource::new_file(file_id.into());
     module_from_source(db, module_source)
 }
 
@@ -36,7 +34,7 @@ pub fn module_from_declaration(
     let child_name = decl.name();
     match (parent_module, child_name) {
         (Some(parent_module), Some(child_name)) => {
-            if let Some(child) = parent_module.child(db, &child_name.as_name())? {
+            if let Some(child) = parent_module.child(&child_name.as_name()) {
                 return Ok(Some(child));
             }
         }
@@ -51,26 +49,11 @@ pub fn module_from_position(
     position: FilePosition,
 ) -> Cancelable<Option<Module>> {
     let file = db.source_file(position.file_id);
-    match find_node_at_offset::<ast::Module>(file.syntax(), position.offset) {
-        Some(m) if !m.has_semi() => module_from_inline(db, position.file_id.into(), m),
-        _ => module_from_file_id(db, position.file_id.into()),
-    }
-}
-
-fn module_from_inline(
-    db: &impl HirDatabase,
-    file_id: FileId,
-    module: ast::Module,
-) -> Cancelable<Option<Module>> {
-    assert!(!module.has_semi());
-    let file_id = file_id.into();
-    let file_items = db.file_items(file_id);
-    let item_id = file_items.id_of(file_id, module.syntax());
-    let source = SourceItemId {
-        file_id,
-        item_id: Some(item_id),
+    let module_source = match find_node_at_offset::<ast::Module>(file.syntax(), position.offset) {
+        Some(m) if !m.has_semi() => ModuleSource::new_inline(db, position.file_id.into(), m),
+        _ => ModuleSource::new_file(position.file_id.into()),
     };
-    module_from_source(db, source)
+    module_from_source(db, module_source)
 }
 
 /// Locates the module by child syntax element within the module
@@ -79,34 +62,29 @@ pub fn module_from_child_node(
     file_id: FileId,
     child: SyntaxNodeRef,
 ) -> Cancelable<Option<Module>> {
-    if let Some(m) = child
+    let module_source = if let Some(m) = child
         .ancestors()
         .filter_map(ast::Module::cast)
         .find(|it| !it.has_semi())
     {
-        module_from_inline(db, file_id.into(), m)
+        ModuleSource::new_inline(db, file_id.into(), m)
     } else {
-        module_from_file_id(db, file_id.into())
-    }
-}
-
-fn module_from_source(db: &impl HirDatabase, source: SourceItemId) -> Cancelable<Option<Module>> {
-    let source_root_id = db.file_source_root(source.file_id.as_original_file());
-    let module_tree = db.module_tree(source_root_id)?;
-    let module_id = ctry!(module_tree.find_module_by_source(source));
-    Ok(Some(Module::from_module_id(db, source_root_id, module_id)?))
+        ModuleSource::new_file(file_id.into())
+    };
+    module_from_source(db, module_source)
 }
 
-pub fn function_from_position(
+fn module_from_source(
     db: &impl HirDatabase,
-    position: FilePosition,
-) -> Cancelable<Option<Function>> {
-    let file = db.source_file(position.file_id);
-    let fn_def = ctry!(find_node_at_offset::<ast::FnDef>(
-        file.syntax(),
-        position.offset
-    ));
-    function_from_source(db, position.file_id, fn_def)
+    module_source: ModuleSource,
+) -> Cancelable<Option<Module>> {
+    let source_root_id = db.file_source_root(module_source.file_id().as_original_file());
+    let module_tree = db.module_tree(source_root_id)?;
+    let m = module_tree
+        .modules_with_sources()
+        .find(|(_id, src)| src == &module_source);
+    let module_id = ctry!(m).0;
+    Ok(Some(Module::new(db, source_root_id, module_id)?))
 }
 
 pub fn function_from_source(
@@ -124,8 +102,7 @@ pub fn function_from_module(
     module: &Module,
     fn_def: ast::FnDef,
 ) -> Function {
-    let loc = module.def_id.loc(db);
-    let file_id = loc.source_item_id.file_id;
+    let file_id = module.source().file_id();
     let file_items = db.file_items(file_id);
     let item_id = file_items.id_of(file_id, fn_def.syntax());
     let source_item_id = SourceItemId {
@@ -134,8 +111,8 @@ pub fn function_from_module(
     };
     let def_loc = DefLoc {
         kind: DefKind::Function,
-        source_root_id: loc.source_root_id,
-        module_id: loc.module_id,
+        source_root_id: module.source_root_id,
+        module_id: module.module_id,
         source_item_id,
     };
     Function::new(def_loc.id(db))
@@ -158,8 +135,7 @@ pub fn macro_symbols(
         Some(it) => it,
         None => return Ok(Vec::new()),
     };
-    let loc = module.def_id.loc(db);
-    let items = db.input_module_items(loc.source_root_id, loc.module_id)?;
+    let items = db.input_module_items(module.source_root_id, module.module_id)?;
     let mut res = Vec::new();
 
     for macro_call_id in items
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index 8c320a7053..8f56cdb151 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -26,16 +26,15 @@ use ena::unify::{InPlaceUnificationTable, UnifyKey, UnifyValue, NoError};
 
 use ra_db::{LocalSyntaxPtr, Cancelable};
 use ra_syntax::{
-    ast::{self, AstNode, LoopBodyOwner, ArgListOwner, PrefixOp},
+    ast::{self, AstNode, LoopBodyOwner, ArgListOwner, PrefixOp, BinOp},
     SyntaxNodeRef
 };
 
 use crate::{
-    Def, DefId, Module, Function, Struct, Enum, Path, Name, AsName, ImplBlock,
+    Def, DefId, FnScopes, Module, Function, Struct, Enum, Path, Name, AsName, ImplBlock,
     db::HirDatabase,
     type_ref::{TypeRef, Mutability},
     name::KnownName,
-    ScopesWithSyntaxMapping,
 };
 
 /// The ID of a type variable.
@@ -306,7 +305,7 @@ impl Ty {
                 return Ok(Ty::Uint(uint_ty));
             } else if let Some(float_ty) = primitive::FloatTy::from_name(name) {
                 return Ok(Ty::Float(float_ty));
-            } else if name.as_known_name() == Some(KnownName::SelfType) {
+            } else if name.as_known_name() == Some(KnownName::Self_) {
                 return Ty::from_hir_opt(db, module, None, impl_block.map(|i| i.target_type()));
             }
         }
@@ -516,7 +515,7 @@ impl InferenceResult {
 #[derive(Clone, Debug)]
 struct InferenceContext<'a, D: HirDatabase> {
     db: &'a D,
-    scopes: ScopesWithSyntaxMapping,
+    scopes: Arc<FnScopes>,
     /// The self param for the current method, if it exists.
     self_param: Option<LocalSyntaxPtr>,
     module: Module,
@@ -527,10 +526,24 @@ struct InferenceContext<'a, D: HirDatabase> {
     return_ty: Ty,
 }
 
+// helper function that determines whether a binary operator
+// always returns a boolean
+fn is_boolean_operator(op: BinOp) -> bool {
+    match op {
+        BinOp::BooleanOr
+        | BinOp::BooleanAnd
+        | BinOp::EqualityTest
+        | BinOp::LesserEqualTest
+        | BinOp::GreaterEqualTest
+        | BinOp::LesserTest
+        | BinOp::GreaterTest => true,
+    }
+}
+
 impl<'a, D: HirDatabase> InferenceContext<'a, D> {
     fn new(
         db: &'a D,
-        scopes: ScopesWithSyntaxMapping,
+        scopes: Arc<FnScopes>,
         module: Module,
         impl_block: Option<ImplBlock>,
     ) -> Self {
@@ -827,6 +840,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
                 self.infer_expr_opt(e.expr(), &Expectation::none())?;
                 Ty::Never
             }
+            ast::Expr::MatchArmList(_) | ast::Expr::MatchArm(_) | ast::Expr::MatchGuard(_) => {
+                // Can this even occur outside of a match expression?
+                Ty::Unknown
+            }
             ast::Expr::StructLit(e) => {
                 let (ty, def_id) = self.resolve_variant(e.path())?;
                 if let Some(nfl) = e.named_field_list() {
@@ -842,6 +859,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
                 }
                 ty
             }
+            ast::Expr::NamedFieldList(_) | ast::Expr::NamedField(_) => {
+                // Can this even occur outside of a struct literal?
+                Ty::Unknown
+            }
             ast::Expr::IndexExpr(_e) => Ty::Unknown,
             ast::Expr::FieldExpr(e) => {
                 let receiver_ty = self.infer_expr_opt(e.expr(), &Expectation::none())?;
@@ -899,7 +920,24 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
                 }
             }
             ast::Expr::RangeExpr(_e) => Ty::Unknown,
-            ast::Expr::BinExpr(_e) => Ty::Unknown,
+            ast::Expr::BinExpr(e) => match e.op() {
+                Some(op) => {
+                    let subtype_expectation = match op {
+                        BinOp::BooleanAnd | BinOp::BooleanOr => Expectation::has_type(Ty::Bool),
+                        _ => Expectation::none(),
+                    };
+                    let (lhs, rhs) = e.sub_exprs();
+                    let _lhs_ty = self.infer_expr_opt(lhs, &subtype_expectation)?;
+                    let _rhs_ty = self.infer_expr_opt(rhs, &subtype_expectation)?;
+
+                    if is_boolean_operator(op) {
+                        Ty::Bool
+                    } else {
+                        Ty::Unknown
+                    }
+                }
+                _ => Ty::Unknown,
+            },
             ast::Expr::Literal(_e) => Ty::Unknown,
         };
         // use a new type variable if we got Ty::Unknown here
@@ -1009,7 +1047,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
 
 pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceResult>> {
     let function = Function::new(def_id); // TODO: consts also need inference
-    let scopes = function.scopes(db)?;
+    let scopes = function.scopes(db);
     let module = function.module(db)?;
     let impl_block = function.impl_block(db)?;
     let mut ctx = InferenceContext::new(db, scopes, module, impl_block);
diff --git a/crates/ra_hir/src/type_ref.rs b/crates/ra_hir/src/type_ref.rs
index 859f330c24..b36bb35d89 100644
--- a/crates/ra_hir/src/type_ref.rs
+++ b/crates/ra_hir/src/type_ref.rs
@@ -107,8 +107,4 @@ impl TypeRef {
             TypeRef::Error
         }
     }
-
-    pub fn unit() -> TypeRef {
-        TypeRef::Tuple(Vec::new())
-    }
 }
diff --git a/crates/ra_syntax/src/ast.rs b/crates/ra_syntax/src/ast.rs
index c10169d90a..9df8ec6637 100644
--- a/crates/ra_syntax/src/ast.rs
+++ b/crates/ra_syntax/src/ast.rs
@@ -488,6 +488,58 @@ impl<'a> PrefixExpr<'a> {
     }
 }
 
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
+pub enum BinOp {
+    /// The `||` operator for boolean OR
+    BooleanOr,
+    /// The `&&` operator for boolean AND
+    BooleanAnd,
+    /// The `==` operator for equality testing
+    EqualityTest,
+    /// The `<=` operator for lesser-equal testing
+    LesserEqualTest,
+    /// The `>=` operator for greater-equal testing
+    GreaterEqualTest,
+    /// The `<` operator for comparison
+    LesserTest,
+    /// The `>` operator for comparison
+    GreaterTest,
+    // TODO: lots of others
+}
+
+impl<'a> BinExpr<'a> {
+    pub fn op(&self) -> Option<BinOp> {
+        self.syntax()
+            .children()
+            .filter_map(|c| match c.kind() {
+                PIPEPIPE => Some(BinOp::BooleanOr),
+                AMPAMP => Some(BinOp::BooleanAnd),
+                EQEQ => Some(BinOp::EqualityTest),
+                LTEQ => Some(BinOp::LesserEqualTest),
+                GTEQ => Some(BinOp::GreaterEqualTest),
+                L_ANGLE => Some(BinOp::LesserTest),
+                R_ANGLE => Some(BinOp::GreaterTest),
+                _ => None,
+            })
+            .next()
+    }
+
+    pub fn lhs(self) -> Option<Expr<'a>> {
+        children(self).nth(0)
+    }
+
+    pub fn rhs(self) -> Option<Expr<'a>> {
+        children(self).nth(1)
+    }
+
+    pub fn sub_exprs(self) -> (Option<Expr<'a>>, Option<Expr<'a>>) {
+        let mut children = children(self);
+        let first = children.next();
+        let second = children.next();
+        (first, second)
+    }
+}
+
 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 pub enum SelfParamFlavor {
     /// self
diff --git a/crates/ra_syntax/src/ast/generated.rs b/crates/ra_syntax/src/ast/generated.rs
index 24f72393a3..7df6a9c466 100644
--- a/crates/ra_syntax/src/ast/generated.rs
+++ b/crates/ra_syntax/src/ast/generated.rs
@@ -378,11 +378,7 @@ impl<R: TreeRoot<RaTypes>> BreakExprNode<R> {
 }
 
 
-impl<'a> BreakExpr<'a> {
-    pub fn expr(self) -> Option<Expr<'a>> {
-        super::child_opt(self)
-    }
-}
+impl<'a> BreakExpr<'a> {}
 
 // Byte
 #[derive(Debug, Clone, Copy,)]
@@ -927,7 +923,12 @@ pub enum Expr<'a> {
     BlockExpr(BlockExpr<'a>),
     ReturnExpr(ReturnExpr<'a>),
     MatchExpr(MatchExpr<'a>),
+    MatchArmList(MatchArmList<'a>),
+    MatchArm(MatchArm<'a>),
+    MatchGuard(MatchGuard<'a>),
     StructLit(StructLit<'a>),
+    NamedFieldList(NamedFieldList<'a>),
+    NamedField(NamedField<'a>),
     CallExpr(CallExpr<'a>),
     IndexExpr(IndexExpr<'a>),
     MethodCallExpr(MethodCallExpr<'a>),
@@ -959,7 +960,12 @@ impl<'a> AstNode<'a> for Expr<'a> {
             BLOCK_EXPR => Some(Expr::BlockExpr(BlockExpr { syntax })),
             RETURN_EXPR => Some(Expr::ReturnExpr(ReturnExpr { syntax })),
             MATCH_EXPR => Some(Expr::MatchExpr(MatchExpr { syntax })),
+            MATCH_ARM_LIST => Some(Expr::MatchArmList(MatchArmList { syntax })),
+            MATCH_ARM => Some(Expr::MatchArm(MatchArm { syntax })),
+            MATCH_GUARD => Some(Expr::MatchGuard(MatchGuard { syntax })),
             STRUCT_LIT => Some(Expr::StructLit(StructLit { syntax })),
+            NAMED_FIELD_LIST => Some(Expr::NamedFieldList(NamedFieldList { syntax })),
+            NAMED_FIELD => Some(Expr::NamedField(NamedField { syntax })),
             CALL_EXPR => Some(Expr::CallExpr(CallExpr { syntax })),
             INDEX_EXPR => Some(Expr::IndexExpr(IndexExpr { syntax })),
             METHOD_CALL_EXPR => Some(Expr::MethodCallExpr(MethodCallExpr { syntax })),
@@ -991,7 +997,12 @@ impl<'a> AstNode<'a> for Expr<'a> {
             Expr::BlockExpr(inner) => inner.syntax(),
             Expr::ReturnExpr(inner) => inner.syntax(),
             Expr::MatchExpr(inner) => inner.syntax(),
+            Expr::MatchArmList(inner) => inner.syntax(),
+            Expr::MatchArm(inner) => inner.syntax(),
+            Expr::MatchGuard(inner) => inner.syntax(),
             Expr::StructLit(inner) => inner.syntax(),
+            Expr::NamedFieldList(inner) => inner.syntax(),
+            Expr::NamedField(inner) => inner.syntax(),
             Expr::CallExpr(inner) => inner.syntax(),
             Expr::IndexExpr(inner) => inner.syntax(),
             Expr::MethodCallExpr(inner) => inner.syntax(),
@@ -3869,10 +3880,6 @@ impl<'a> StructLit<'a> {
     pub fn named_field_list(self) -> Option<NamedFieldList<'a>> {
         super::child_opt(self)
     }
-
-    pub fn spread(self) -> Option<Expr<'a>> {
-        super::child_opt(self)
-    }
 }
 
 // StructPat
@@ -4140,15 +4147,7 @@ impl<R: TreeRoot<RaTypes>> TupleStructPatNode<R> {
 }
 
 
-impl<'a> TupleStructPat<'a> {
-    pub fn args(self) -> impl Iterator<Item = Pat<'a>> + 'a {
-        super::children(self)
-    }
-
-    pub fn path(self) -> Option<Path<'a>> {
-        super::child_opt(self)
-    }
-}
+impl<'a> TupleStructPat<'a> {}
 
 // TupleType
 #[derive(Debug, Clone, Copy,)]
diff --git a/crates/ra_syntax/src/grammar.ron b/crates/ra_syntax/src/grammar.ron
index 3c640ed47e..c55e9e07a8 100644
--- a/crates/ra_syntax/src/grammar.ron
+++ b/crates/ra_syntax/src/grammar.ron
@@ -384,7 +384,7 @@ Grammar(
             options: [ "Condition" ]
         ),
         "ContinueExpr": (),
-        "BreakExpr": (options: ["Expr"]),
+        "BreakExpr": (),
         "Label": (),
         "BlockExpr": (
             options: [ "Block" ]
@@ -404,7 +404,7 @@ Grammar(
             collections: [ [ "pats", "Pat" ] ]
         ),
         "MatchGuard": (),
-        "StructLit": (options: ["Path", "NamedFieldList", ["spread", "Expr"]]),
+        "StructLit": (options: ["Path", "NamedFieldList"]),
         "NamedFieldList": (collections: [ ["fields", "NamedField"] ]),
         "NamedField": (options: ["NameRef", "Expr"]),
         "CallExpr": (
@@ -446,7 +446,12 @@ Grammar(
                 "BlockExpr",
                 "ReturnExpr",
                 "MatchExpr",
+                "MatchArmList",
+                "MatchArm",
+                "MatchGuard",
                 "StructLit",
+                "NamedFieldList",
+                "NamedField",
                 "CallExpr",
                 "IndexExpr",
                 "MethodCallExpr",
@@ -467,10 +472,7 @@ Grammar(
         "PathPat": (),
         "StructPat": (),
         "FieldPatList": (),
-        "TupleStructPat": (
-            options: ["Path"],
-            collections: [["args", "Pat"]],
-        ),
+        "TupleStructPat": (),
         "TuplePat": (),
         "SlicePat": (),
         "RangePat": (),


Test patch:
diff --git a/crates/ra_analysis/tests/test/main.rs b/crates/ra_analysis/tests/test/main.rs
index 1f70af12aa..26da7c10c9 100644
--- a/crates/ra_analysis/tests/test/main.rs
+++ b/crates/ra_analysis/tests/test/main.rs
@@ -31,7 +31,6 @@ fn test_unresolved_module_diagnostic() {
     );
 }
 
-// FIXME: move this test to hir
 #[test]
 fn test_unresolved_module_diagnostic_no_diag_for_inline_mode() {
     let (analysis, file_id) = single_file("mod foo {}");
@@ -70,7 +69,7 @@ fn test_resolve_parent_module_for_inline() {
     );
     let symbols = analysis.parent_module(pos).unwrap();
     assert_eq_dbg(
-        r#"[NavigationTarget { file_id: FileId(1), name: "baz", kind: MODULE, range: [36; 39), ptr: None }]"#,
+        r#"[NavigationTarget { file_id: FileId(1), name: "bar", kind: MODULE, range: [18; 21), ptr: None }]"#,
         &symbols,
     );
 }
diff --git a/crates/ra_hir/src/nameres/tests.rs b/crates/ra_hir/src/module/nameres/tests.rs
similarity index 98%
rename from crates/ra_hir/src/nameres/tests.rs
rename to crates/ra_hir/src/module/nameres/tests.rs
index dcbe65aec3..a6a0bea316 100644
--- a/crates/ra_hir/src/nameres/tests.rs
+++ b/crates/ra_hir/src/module/nameres/tests.rs
@@ -17,7 +17,7 @@ fn item_map(fixture: &str) -> (Arc<hir::ItemMap>, hir::ModuleId) {
     let module = hir::source_binder::module_from_position(&db, pos)
         .unwrap()
         .unwrap();
-    let module_id = module.def_id.loc(&db).module_id;
+    let module_id = module.module_id;
     (db.item_map(source_root).unwrap(), module_id)
 }
 
@@ -155,7 +155,7 @@ fn item_map_across_crates() {
     let module = hir::source_binder::module_from_file_id(&db, main_id)
         .unwrap()
         .unwrap();
-    let module_id = module.def_id.loc(&db).module_id;
+    let module_id = module.module_id;
     let item_map = db.item_map(source_root).unwrap();
 
     check_module_item_map(
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs
index 515c66e851..1650606b71 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir/src/ty/tests.rs
@@ -1,10 +1,7 @@
-use std::sync::Arc;
 use std::fmt::Write;
 use std::path::{PathBuf, Path};
 use std::fs;
 
-use salsa::Database;
-
 use ra_db::{SyntaxDatabase};
 use ra_syntax::ast::{self, AstNode};
 use test_utils::{project_dir, assert_eq_text, read_text};
@@ -156,6 +153,30 @@ impl S {
     );
 }
 
+#[test]
+fn infer_boolean_op() {
+    check_inference(
+        r#"
+fn f(x: bool) -> i32 {
+    0i32
+}
+
+fn test() {
+    let x = a && b;
+    let y = true || false;
+    let z = x == y;
+    let h = CONST_1 <= CONST_2;
+    let c = f(z || y) + 5;
+    let d = b;
+    let e = 3i32 && "hello world";
+
+    10 < 3
+}
+"#,
+        "0008_boolean_op.txt",
+    );
+}
+
 fn infer(content: &str) -> String {
     let (db, _, file_id) = MockDatabase::with_single_file(content);
     let source_file = db.source_file(file_id);
@@ -220,44 +241,3 @@ fn ellipsize(mut text: String, max_len: usize) -> String {
 fn test_data_dir() -> PathBuf {
     project_dir().join("crates/ra_hir/src/ty/tests/data")
 }
-
-#[test]
-#[should_panic] // TODO this should work once hir::Expr is used
-fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
-    let (mut db, pos) = MockDatabase::with_position(
-        "
-        //- /lib.rs
-        fn foo() -> i32 {
-            <|>1 + 1
-        }
-    ",
-    );
-    let func = source_binder::function_from_position(&db, pos)
-        .unwrap()
-        .unwrap();
-    {
-        let events = db.log_executed(|| {
-            func.infer(&db).unwrap();
-        });
-        assert!(format!("{:?}", events).contains("infer"))
-    }
-
-    let new_text = "
-        fn foo() -> i32 {
-            1
-            +
-            1
-        }
-    "
-    .to_string();
-
-    db.query_mut(ra_db::FileTextQuery)
-        .set(pos.file_id, Arc::new(new_text));
-
-    {
-        let events = db.log_executed(|| {
-            func.infer(&db).unwrap();
-        });
-        assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
-    }
-}
diff --git a/crates/ra_hir/src/ty/tests/data/0008_boolean_op.txt b/crates/ra_hir/src/ty/tests/data/0008_boolean_op.txt
new file mode 100644
index 0000000000..ca01ad1593
--- /dev/null
+++ b/crates/ra_hir/src/ty/tests/data/0008_boolean_op.txt
@@ -0,0 +1,31 @@
+[28; 32) '0i32': i32
+[22; 34) '{     0i32 }': i32
+[6; 7) 'x': [unknown]
+[127; 134) 'CONST_1': [unknown]
+[201; 205) '3i32': bool
+[76; 77) 'y': bool
+[65; 66) 'b': bool
+[60; 66) 'a && b': bool
+[127; 145) 'CONST_...ONST_2': bool
+[182; 183) 'd': [unknown]
+[229; 231) '10': [unknown]
+[209; 222) '"hello world"': bool
+[229; 235) '10 < 3': bool
+[186; 187) 'b': [unknown]
+[159; 172) 'f(z || y) + 5': [unknown]
+[56; 57) 'x': bool
+[112; 113) 'y': bool
+[201; 222) '3i32 &...world"': bool
+[234; 235) '3': [unknown]
+[138; 145) 'CONST_2': [unknown]
+[80; 93) 'true || false': bool
+[46; 237) '{     ... < 3 }': bool
+[197; 198) 'e': bool
+[107; 113) 'x == y': bool
+[88; 93) 'false': bool
+[80; 84) 'true': bool
+[123; 124) 'h': bool
+[155; 156) 'c': [unknown]
+[103; 104) 'z': bool
+[60; 61) 'a': bool
+[107; 108) 'x': bool