aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir')
-rw-r--r--crates/ra_hir/src/expr.rs104
-rw-r--r--crates/ra_hir/src/ids.rs2
-rw-r--r--crates/ra_hir/src/nameres/collector.rs3
-rw-r--r--crates/ra_hir/src/resolve.rs32
-rw-r--r--crates/ra_hir/src/ty/tests.rs26
5 files changed, 112 insertions, 55 deletions
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs
index 7d5257461..db74d28e8 100644
--- a/crates/ra_hir/src/expr.rs
+++ b/crates/ra_hir/src/expr.rs
@@ -5,14 +5,14 @@ use rustc_hash::FxHashMap;
5 5
6use ra_arena::{Arena, RawId, impl_arena_id, map::ArenaMap}; 6use ra_arena::{Arena, RawId, impl_arena_id, map::ArenaMap};
7use ra_syntax::{ 7use ra_syntax::{
8 SyntaxNodePtr, AstPtr, AstNode, 8 SyntaxNodePtr, AstPtr, AstNode,TreeArc,
9 ast::{self, LoopBodyOwner, ArgListOwner, NameOwner, LiteralKind,ArrayExprKind, TypeAscriptionOwner} 9 ast::{self, LoopBodyOwner, ArgListOwner, NameOwner, LiteralKind,ArrayExprKind, TypeAscriptionOwner}
10}; 10};
11 11
12use crate::{ 12use crate::{
13 Path, Name, HirDatabase, Resolver,DefWithBody, Either, 13 Path, Name, HirDatabase, Resolver,DefWithBody, Either,
14 name::AsName, 14 name::AsName,
15 ids::{MacroCallLoc,HirFileId}, 15 ids::{MacroCallId},
16 type_ref::{Mutability, TypeRef}, 16 type_ref::{Mutability, TypeRef},
17}; 17};
18use crate::{path::GenericArgs, ty::primitive::{IntTy, UncertainIntTy, FloatTy, UncertainFloatTy}}; 18use crate::{path::GenericArgs, ty::primitive::{IntTy, UncertainIntTy, FloatTy, UncertainFloatTy}};
@@ -488,23 +488,45 @@ pub(crate) struct ExprCollector<DB> {
488 params: Vec<PatId>, 488 params: Vec<PatId>,
489 body_expr: Option<ExprId>, 489 body_expr: Option<ExprId>,
490 resolver: Resolver, 490 resolver: Resolver,
491 // FIXEME: Its a quick hack,see issue #1196
492 is_in_macro: bool,
491} 493}
492 494
493impl<'a, DB> ExprCollector<&'a DB> 495impl<'a, DB> ExprCollector<&'a DB>
494where 496where
495 DB: HirDatabase, 497 DB: HirDatabase,
496{ 498{
499 fn new(owner: DefWithBody, resolver: Resolver, db: &'a DB) -> Self {
500 ExprCollector {
501 owner,
502 resolver,
503 db,
504 exprs: Arena::default(),
505 pats: Arena::default(),
506 source_map: BodySourceMap::default(),
507 params: Vec::new(),
508 body_expr: None,
509 is_in_macro: false,
510 }
511 }
497 fn alloc_expr(&mut self, expr: Expr, syntax_ptr: SyntaxNodePtr) -> ExprId { 512 fn alloc_expr(&mut self, expr: Expr, syntax_ptr: SyntaxNodePtr) -> ExprId {
498 let id = self.exprs.alloc(expr); 513 let id = self.exprs.alloc(expr);
499 self.source_map.expr_map.insert(syntax_ptr, id); 514 if !self.is_in_macro {
500 self.source_map.expr_map_back.insert(id, syntax_ptr); 515 self.source_map.expr_map.insert(syntax_ptr, id);
516 self.source_map.expr_map_back.insert(id, syntax_ptr);
517 }
518
501 id 519 id
502 } 520 }
503 521
504 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId { 522 fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
505 let id = self.pats.alloc(pat); 523 let id = self.pats.alloc(pat);
506 self.source_map.pat_map.insert(ptr, id); 524
507 self.source_map.pat_map_back.insert(id, ptr); 525 if !self.is_in_macro {
526 self.source_map.pat_map.insert(ptr, id);
527 self.source_map.pat_map_back.insert(id, ptr);
528 }
529
508 id 530 id
509 } 531 }
510 532
@@ -790,40 +812,19 @@ where
790 ast::ExprKind::IndexExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr), 812 ast::ExprKind::IndexExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
791 ast::ExprKind::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr), 813 ast::ExprKind::RangeExpr(_e) => self.alloc_expr(Expr::Missing, syntax_ptr),
792 ast::ExprKind::MacroCall(e) => { 814 ast::ExprKind::MacroCall(e) => {
793 // very hacky.TODO change to use the macro resolution 815 // very hacky.FIXME change to use the macro resolution
794 let name = e 816 let path = e.path().and_then(Path::from_ast);
795 .path() 817
796 .and_then(Path::from_ast) 818 if let Some(call_id) = self.resolver.resolve_macro_call(self.db, path, e) {
797 .and_then(|path| path.expand_macro_expr()) 819 if let Some(expr) = expand_macro_to_expr(self.db, call_id, e.token_tree()) {
798 .unwrap_or_else(Name::missing); 820 log::debug!("macro expansion {}", expr.syntax().debug_dump());
799 821 let old = std::mem::replace(&mut self.is_in_macro, true);
800 if let Some(macro_id) = self.resolver.resolve_macro_call(&name) { 822 let id = self.collect_expr(&expr);
801 if let Some((module, _)) = self.resolver.module() { 823 self.is_in_macro = old;
802 // we do this to get the ast_id for the macro call 824 id
803 // if we used the ast_id from the macro_id variable
804 // it gives us the ast_id of the defenition site
805 let module = module.mk_module(module.root());
806 let hir_file_id = module.definition_source(self.db).0;
807 let ast_id =
808 self.db.ast_id_map(hir_file_id).ast_id(e).with_file_id(hir_file_id);
809
810 let call_loc = MacroCallLoc { def: *macro_id, ast_id };
811 let call_id = call_loc.id(self.db);
812 let file_id: HirFileId = call_id.into();
813
814 log::debug!(
815 "expanded macro ast {}",
816 self.db.hir_parse(file_id).syntax().debug_dump()
817 );
818
819 self.db
820 .hir_parse(file_id)
821 .syntax()
822 .descendants()
823 .find_map(ast::Expr::cast)
824 .map(|expr| self.collect_expr(expr))
825 .unwrap_or(self.alloc_expr(Expr::Missing, syntax_ptr))
826 } else { 825 } else {
826 // FIXME: Instead of just dropping the error from expansion
827 // report it
827 self.alloc_expr(Expr::Missing, syntax_ptr) 828 self.alloc_expr(Expr::Missing, syntax_ptr)
828 } 829 }
829 } else { 830 } else {
@@ -987,20 +988,25 @@ where
987 } 988 }
988} 989}
989 990
991fn expand_macro_to_expr(
992 db: &impl HirDatabase,
993 macro_call: MacroCallId,
994 args: Option<&ast::TokenTree>,
995) -> Option<TreeArc<ast::Expr>> {
996 let rules = db.macro_def(macro_call.loc(db).def)?;
997
998 let args = mbe::ast_to_token_tree(args?)?.0;
999
1000 let expanded = rules.expand(&args).ok()?;
1001
1002 mbe::token_tree_to_expr(&expanded).ok()
1003}
1004
990pub(crate) fn body_with_source_map_query( 1005pub(crate) fn body_with_source_map_query(
991 db: &impl HirDatabase, 1006 db: &impl HirDatabase,
992 def: DefWithBody, 1007 def: DefWithBody,
993) -> (Arc<Body>, Arc<BodySourceMap>) { 1008) -> (Arc<Body>, Arc<BodySourceMap>) {
994 let mut collector = ExprCollector { 1009 let mut collector = ExprCollector::new(def, def.resolver(db), db);
995 db,
996 owner: def,
997 resolver: def.resolver(db),
998 exprs: Arena::default(),
999 pats: Arena::default(),
1000 source_map: BodySourceMap::default(),
1001 params: Vec::new(),
1002 body_expr: None,
1003 };
1004 1010
1005 match def { 1011 match def {
1006 DefWithBody::Const(ref c) => collector.collect_const_body(&c.source(db).1), 1012 DefWithBody::Const(ref c) => collector.collect_const_body(&c.source(db).1),
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs
index a07624a19..c7849c995 100644
--- a/crates/ra_hir/src/ids.rs
+++ b/crates/ra_hir/src/ids.rs
@@ -101,7 +101,7 @@ fn parse_macro(
101 return Err(format!("Total tokens count exceed limit : count = {}", count)); 101 return Err(format!("Total tokens count exceed limit : count = {}", count));
102 } 102 }
103 103
104 Some(mbe::token_tree_to_ast_item_list(&tt)) 104 Ok(mbe::token_tree_to_ast_item_list(&tt))
105} 105}
106 106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs
index 762a61604..b34c9b8e6 100644
--- a/crates/ra_hir/src/nameres/collector.rs
+++ b/crates/ra_hir/src/nameres/collector.rs
@@ -524,7 +524,7 @@ where
524 { 524 {
525 let macro_call_id = MacroCallLoc { def: *macro_id, ast_id }.id(self.def_collector.db); 525 let macro_call_id = MacroCallLoc { def: *macro_id, ast_id }.id(self.def_collector.db);
526 526
527 self.def_collector.collect_macro_expansion(self.module_id, macro_call_id, macro_id); 527 self.def_collector.collect_macro_expansion(self.module_id, macro_call_id, *macro_id);
528 return; 528 return;
529 } 529 }
530 530
@@ -616,6 +616,7 @@ mod tests {
616 modules, 616 modules,
617 public_macros: FxHashMap::default(), 617 public_macros: FxHashMap::default(),
618 poison_macros: FxHashSet::default(), 618 poison_macros: FxHashSet::default(),
619 local_macros: FxHashMap::default(),
619 diagnostics: Vec::new(), 620 diagnostics: Vec::new(),
620 } 621 }
621 }; 622 };
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs
index 1def032f9..d1f97c104 100644
--- a/crates/ra_hir/src/resolve.rs
+++ b/crates/ra_hir/src/resolve.rs
@@ -1,12 +1,15 @@
1//! Name resolution. 1//! Name resolution.
2use std::sync::Arc; 2use std::sync::Arc;
3 3
4use ra_syntax::ast;
5
4use rustc_hash::FxHashMap; 6use rustc_hash::FxHashMap;
5 7
6use crate::{ 8use crate::{
7 ModuleDef, 9 ModuleDef,
8 code_model_api::Crate, 10 code_model_api::Crate,
9 MacroDefId, 11 MacroCallId,
12 MacroCallLoc,
10 db::HirDatabase, 13 db::HirDatabase,
11 name::{Name, KnownName}, 14 name::{Name, KnownName},
12 nameres::{PerNs, CrateDefMap, CrateModuleId}, 15 nameres::{PerNs, CrateDefMap, CrateModuleId},
@@ -131,8 +134,29 @@ impl Resolver {
131 resolution 134 resolution
132 } 135 }
133 136
134 pub fn resolve_macro_call(&self, name: &Name) -> Option<&MacroDefId> { 137 pub fn resolve_macro_call(
135 self.module().and_then(|(module, _)| module.find_macro(name)) 138 &self,
139 db: &impl HirDatabase,
140 path: Option<Path>,
141 call: &ast::MacroCall,
142 ) -> Option<MacroCallId> {
143 let name = path.and_then(|path| path.expand_macro_expr()).unwrap_or_else(Name::missing);
144 let macro_def_id = self.module().and_then(|(module, _)| module.find_macro(&name));
145 if let Some(def_id) = macro_def_id {
146 self.module().and_then(|(module, _)| {
147 // we do this to get the ast_id for the macro call
148 // if we used the ast_id from the def_id variable
149 // it gives us the ast_id of the defenition site
150 let module = module.mk_module(module.root());
151 let hir_file_id = module.definition_source(db).0;
152 let ast_id = db.ast_id_map(hir_file_id).ast_id(call).with_file_id(hir_file_id);
153 let call_loc = MacroCallLoc { def: *def_id, ast_id }.id(db);
154
155 Some(call_loc)
156 })
157 } else {
158 None
159 }
136 } 160 }
137 161
138 /// Returns the resolved path segments 162 /// Returns the resolved path segments
@@ -197,7 +221,7 @@ impl Resolver {
197 .flatten() 221 .flatten()
198 } 222 }
199 223
200 pub(crate) fn module(&self) -> Option<(&CrateDefMap, CrateModuleId)> { 224 fn module(&self) -> Option<(&CrateDefMap, CrateModuleId)> {
201 self.scopes.iter().rev().find_map(|scope| match scope { 225 self.scopes.iter().rev().find_map(|scope| match scope {
202 Scope::ModuleScope(m) => Some((&*m.crate_def_map, m.module_id)), 226 Scope::ModuleScope(m) => Some((&*m.crate_def_map, m.module_id)),
203 227
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs
index a4c99528d..c76a5012f 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir/src/ty/tests.rs
@@ -2417,6 +2417,30 @@ fn test() -> u64 {
2417 ); 2417 );
2418} 2418}
2419 2419
2420#[test]
2421fn infer_macros_expanded() {
2422 assert_snapshot_matches!(
2423 infer(r#"
2424struct Foo(Vec<i32>);
2425
2426macro_rules! foo {
2427 ($($item:expr),*) => {
2428 {
2429 Foo(vec![$($item,)*])
2430 }
2431 };
2432}
2433
2434fn main() {
2435 let x = foo!(1,2);
2436}
2437"#),
2438 @r###"
2439[156; 182) '{ ...,2); }': ()
2440[166; 167) 'x': Foo"###
2441 );
2442}
2443
2420#[ignore] 2444#[ignore]
2421#[test] 2445#[test]
2422fn method_resolution_trait_before_autoref() { 2446fn method_resolution_trait_before_autoref() {
@@ -2510,6 +2534,7 @@ fn type_at(content: &str) -> String {
2510fn infer(content: &str) -> String { 2534fn infer(content: &str) -> String {
2511 let (db, _, file_id) = MockDatabase::with_single_file(content); 2535 let (db, _, file_id) = MockDatabase::with_single_file(content);
2512 let source_file = db.parse(file_id); 2536 let source_file = db.parse(file_id);
2537
2513 let mut acc = String::new(); 2538 let mut acc = String::new();
2514 acc.push_str("\n"); 2539 acc.push_str("\n");
2515 2540
@@ -2532,6 +2557,7 @@ fn infer(content: &str) -> String {
2532 }; 2557 };
2533 types.push((syntax_ptr, ty)); 2558 types.push((syntax_ptr, ty));
2534 } 2559 }
2560
2535 // sort ranges for consistency 2561 // sort ranges for consistency
2536 types.sort_by_key(|(ptr, _)| (ptr.range().start(), ptr.range().end())); 2562 types.sort_by_key(|(ptr, _)| (ptr.range().start(), ptr.range().end()));
2537 for (syntax_ptr, ty) in &types { 2563 for (syntax_ptr, ty) in &types {