]> git.lizzy.rs Git - rust.git/commitdiff
Use block_def_map in body lowering
authorJonas Schievink <jonasschievink@gmail.com>
Mon, 1 Feb 2021 12:19:55 +0000 (13:19 +0100)
committerJonas Schievink <jonasschievink@gmail.com>
Mon, 1 Feb 2021 12:33:18 +0000 (13:33 +0100)
crates/hir_def/src/body.rs
crates/hir_def/src/body/lower.rs
crates/hir_def/src/data.rs
crates/hir_def/src/expr.rs
crates/hir_def/src/item_tree.rs
crates/hir_ty/src/infer/expr.rs

index b9ecf22fa5f20236bead91e87a2583defcdfa614..41abd8f83b5e1f3d7aaac39c67c290f90a32a68a 100644 (file)
@@ -46,7 +46,7 @@ pub(crate) struct CfgExpander {
 
 pub(crate) struct Expander {
     cfg_expander: CfgExpander,
-    crate_def_map: Arc<DefMap>,
+    def_map: Arc<DefMap>,
     current_file_id: HirFileId,
     ast_id_map: Arc<AstIdMap>,
     module: ModuleId,
@@ -91,7 +91,7 @@ pub(crate) fn new(
         let ast_id_map = db.ast_id_map(current_file_id);
         Expander {
             cfg_expander,
-            crate_def_map,
+            def_map: crate_def_map,
             current_file_id,
             ast_id_map,
             module,
@@ -102,7 +102,6 @@ pub(crate) fn new(
     pub(crate) fn enter_expand<T: ast::AstNode>(
         &mut self,
         db: &dyn DefDatabase,
-        local_scope: Option<&ItemScope>,
         macro_call: ast::MacroCall,
     ) -> ExpandResult<Option<(Mark, T)>> {
         if self.recursion_limit + 1 > EXPANSION_RECURSION_LIMIT {
@@ -112,18 +111,12 @@ pub(crate) fn enter_expand<T: ast::AstNode>(
 
         let macro_call = InFile::new(self.current_file_id, &macro_call);
 
-        let resolver = |path: ModPath| -> Option<MacroDefId> {
-            if let Some(local_scope) = local_scope {
-                if let Some(def) = path.as_ident().and_then(|n| local_scope.get_legacy_macro(n)) {
-                    return Some(def);
-                }
-            }
-            self.resolve_path_as_macro(db, &path)
-        };
+        let resolver =
+            |path: ModPath| -> Option<MacroDefId> { self.resolve_path_as_macro(db, &path) };
 
         let mut err = None;
         let call_id =
-            macro_call.as_call_id_with_errors(db, self.crate_def_map.krate(), resolver, &mut |e| {
+            macro_call.as_call_id_with_errors(db, self.def_map.krate(), resolver, &mut |e| {
                 err.get_or_insert(e);
             });
         let call_id = match call_id {
@@ -204,7 +197,7 @@ fn parse_path(&mut self, path: ast::Path) -> Option<Path> {
     }
 
     fn resolve_path_as_macro(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<MacroDefId> {
-        self.crate_def_map
+        self.def_map
             .resolve_path(db, self.module.local_id, path, BuiltinShadowMode::Other)
             .0
             .take_macros()
index 209965fcaf74116de7d5e97e0246c8fdbc6ff20e..bc61730a7a97530f6d82c84f93923c05aa49de71 100644 (file)
@@ -1,7 +1,7 @@
 //! Transforms `ast::Expr` into an equivalent `hir_def::expr::Expr`
 //! representation.
 
-use std::{any::type_name, sync::Arc};
+use std::{any::type_name, mem, sync::Arc};
 
 use either::Either;
 use hir_expand::{
@@ -36,8 +36,8 @@
     item_tree::{ItemTree, ItemTreeId, ItemTreeNode},
     path::{GenericArgs, Path},
     type_ref::{Mutability, Rawness, TypeRef},
-    AdtId, ConstLoc, ContainerId, DefWithBodyId, EnumLoc, FunctionLoc, Intern, ModuleDefId,
-    StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
+    AdtId, BlockLoc, ConstLoc, ContainerId, DefWithBodyId, EnumLoc, FunctionLoc, Intern,
+    ModuleDefId, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
 };
 
 use super::{diagnostics::BodyDiagnostic, ExprSource, PatSource};
@@ -152,8 +152,8 @@ fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
     fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
         self.make_expr(expr, Err(SyntheticSyntax))
     }
-    fn empty_block(&mut self) -> ExprId {
-        self.alloc_expr_desugared(Expr::Block { statements: Vec::new(), tail: None, label: None })
+    fn unit(&mut self) -> ExprId {
+        self.alloc_expr_desugared(Expr::Tuple { exprs: Vec::new() })
     }
     fn missing_expr(&mut self) -> ExprId {
         self.alloc_expr_desugared(Expr::Missing)
@@ -222,7 +222,7 @@ fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
                                 MatchArm { pat, expr: then_branch, guard: None },
                                 MatchArm {
                                     pat: placeholder_pat,
-                                    expr: else_branch.unwrap_or_else(|| self.empty_block()),
+                                    expr: else_branch.unwrap_or_else(|| self.unit()),
                                     guard: None,
                                 },
                             ];
@@ -561,7 +561,7 @@ fn collect_macro_call<F: FnMut(&mut Self, Option<T>), T: ast::AstNode>(
         let outer_file = self.expander.current_file_id;
 
         let macro_call = self.expander.to_source(AstPtr::new(&e));
-        let res = self.expander.enter_expand(self.db, Some(&self.body.item_scope), e);
+        let res = self.expander.enter_expand(self.db, e);
 
         match &res.err {
             Some(ExpandError::UnresolvedProcMacro) => {
@@ -697,12 +697,27 @@ fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Vec<Statement>> {
     }
 
     fn collect_block(&mut self, block: ast::BlockExpr) -> ExprId {
-        let syntax_node_ptr = AstPtr::new(&block.clone().into());
+        let ast_id = self.expander.ast_id(&block);
+        let block_loc = BlockLoc { ast_id, module: self.expander.module };
+        let block_id = self.db.intern_block(block_loc);
+        let def_map = self.db.block_def_map(block_id);
+        let root = def_map.module_id(def_map.root());
+        let prev_def_map = mem::replace(&mut self.expander.def_map, def_map);
+        let prev_module = mem::replace(&mut self.expander.module, root);
+
         self.collect_stmts_items(block.statements());
         let statements =
             block.statements().filter_map(|s| self.collect_stmt(s)).flatten().collect();
         let tail = block.tail_expr().map(|e| self.collect_expr(e));
-        self.alloc_expr(Expr::Block { statements, tail, label: None }, syntax_node_ptr)
+        let syntax_node_ptr = AstPtr::new(&block.clone().into());
+        let expr_id = self.alloc_expr(
+            Expr::Block { id: block_id, statements, tail, label: None },
+            syntax_node_ptr,
+        );
+
+        self.expander.def_map = prev_def_map;
+        self.expander.module = prev_module;
+        expr_id
     }
 
     fn collect_stmts_items(&mut self, stmts: ast::AstChildren<ast::Stmt>) {
@@ -832,7 +847,7 @@ fn collect_pat(&mut self, pat: ast::Pat) -> PatId {
                 if annotation == BindingAnnotation::Unannotated && subpat.is_none() {
                     // This could also be a single-segment path pattern. To
                     // decide that, we need to try resolving the name.
-                    let (resolved, _) = self.expander.crate_def_map.resolve_path(
+                    let (resolved, _) = self.expander.def_map.resolve_path(
                         self.db,
                         self.expander.module.local_id,
                         &name.clone().into(),
index e7b7724f75fb245157d55f4d7e144673b0c17560..c2b0dc00714a9e1fae5345f439170ce47300c6e7 100644 (file)
@@ -262,7 +262,7 @@ fn collect_items(
                 let root = db.parse_or_expand(file_id).unwrap();
                 let call = ast_id_map.get(call.ast_id).to_node(&root);
 
-                if let Some((mark, mac)) = expander.enter_expand(db, None, call).value {
+                if let Some((mark, mac)) = expander.enter_expand(db, call).value {
                     let src: InFile<ast::MacroItems> = expander.to_source(mac);
                     let item_tree = db.item_tree(src.file_id);
                     let iter =
index 5be838f4a7d842ae7fb45011eebadae56e5ea011..4d72eaeaff9aa4269d9d42bdb102b993a977d101 100644 (file)
@@ -20,6 +20,7 @@
     builtin_type::{BuiltinFloat, BuiltinInt},
     path::{GenericArgs, Path},
     type_ref::{Mutability, Rawness, TypeRef},
+    BlockId,
 };
 
 pub type ExprId = Idx<Expr>;
@@ -56,6 +57,7 @@ pub enum Expr {
         else_branch: Option<ExprId>,
     },
     Block {
+        id: BlockId,
         statements: Vec<Statement>,
         tail: Option<ExprId>,
         label: Option<LabelId>,
index 42d9f09472dab3abc77d9a56c028d6b203c4cffb..4bde676490ec2a613a3cc548dddf0e08b6f790bc 100644 (file)
@@ -24,7 +24,7 @@
 use profile::Count;
 use rustc_hash::FxHashMap;
 use smallvec::SmallVec;
-use syntax::{ast, match_ast};
+use syntax::{ast, match_ast, SyntaxKind};
 use test_utils::mark;
 
 use crate::{
@@ -80,6 +80,10 @@ impl ItemTree {
     pub(crate) fn item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
         let _p = profile::span("item_tree_query").detail(|| format!("{:?}", file_id));
         let syntax = if let Some(node) = db.parse_or_expand(file_id) {
+            if node.kind() == SyntaxKind::ERROR {
+                // FIXME: not 100% sure why these crop up, but return an empty tree to avoid a panic
+                return Default::default();
+            }
             node
         } else {
             return Default::default();
index d7351d21270193138c6d380e1f894648d4b9dfd3..12f1591c81f266b2d2a09f64aa33c9e78c77b109 100644 (file)
@@ -137,7 +137,7 @@ fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty {
 
                 self.coerce_merge_branch(&then_ty, &else_ty)
             }
-            Expr::Block { statements, tail, label } => match label {
+            Expr::Block { statements, tail, label, id: _ } => match label {
                 Some(_) => {
                     let break_ty = self.table.new_type_var();
                     self.breakables.push(BreakableContext {