aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock8
-rw-r--r--crates/ra_hir/Cargo.toml2
-rw-r--r--crates/ra_hir/src/db.rs44
-rw-r--r--crates/ra_hir/src/debug.rs6
-rw-r--r--crates/ra_hir/src/expr/lower.rs2
-rw-r--r--crates/ra_hir/src/ids.rs204
-rw-r--r--crates/ra_hir/src/impl_block.rs2
-rw-r--r--crates/ra_hir/src/lib.rs14
-rw-r--r--crates/ra_hir/src/nameres/collector.rs7
-rw-r--r--crates/ra_hir/src/path.rs9
-rw-r--r--crates/ra_hir/src/source_id.rs73
-rw-r--r--crates/ra_hir_def/src/lib.rs7
-rw-r--r--crates/ra_hir_expand/Cargo.toml (renamed from crates/ra_hir_def/Cargo.toml)7
-rw-r--r--crates/ra_hir_expand/src/ast_id_map.rs (renamed from crates/ra_hir_def/src/ast_id_map.rs)36
-rw-r--r--crates/ra_hir_expand/src/db.rs104
-rw-r--r--crates/ra_hir_expand/src/lib.rs161
-rw-r--r--crates/ra_ide_api/Cargo.toml5
17 files changed, 338 insertions, 353 deletions
diff --git a/Cargo.lock b/Cargo.lock
index ff3362be9..18d2fb9d5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1003,7 +1003,7 @@ dependencies = [
1003 "ra_arena 0.1.0", 1003 "ra_arena 0.1.0",
1004 "ra_cfg 0.1.0", 1004 "ra_cfg 0.1.0",
1005 "ra_db 0.1.0", 1005 "ra_db 0.1.0",
1006 "ra_hir_def 0.1.0", 1006 "ra_hir_expand 0.1.0",
1007 "ra_mbe 0.1.0", 1007 "ra_mbe 0.1.0",
1008 "ra_prof 0.1.0", 1008 "ra_prof 0.1.0",
1009 "ra_syntax 0.1.0", 1009 "ra_syntax 0.1.0",
@@ -1014,12 +1014,16 @@ dependencies = [
1014] 1014]
1015 1015
1016[[package]] 1016[[package]]
1017name = "ra_hir_def" 1017name = "ra_hir_expand"
1018version = "0.1.0" 1018version = "0.1.0"
1019dependencies = [ 1019dependencies = [
1020 "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
1020 "ra_arena 0.1.0", 1021 "ra_arena 0.1.0",
1021 "ra_db 0.1.0", 1022 "ra_db 0.1.0",
1023 "ra_mbe 0.1.0",
1024 "ra_prof 0.1.0",
1022 "ra_syntax 0.1.0", 1025 "ra_syntax 0.1.0",
1026 "ra_tt 0.1.0",
1023] 1027]
1024 1028
1025[[package]] 1029[[package]]
diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml
index 67f8c4946..143dae6bd 100644
--- a/crates/ra_hir/Cargo.toml
+++ b/crates/ra_hir/Cargo.toml
@@ -19,7 +19,7 @@ ra_cfg = { path = "../ra_cfg" }
19ra_db = { path = "../ra_db" } 19ra_db = { path = "../ra_db" }
20mbe = { path = "../ra_mbe", package = "ra_mbe" } 20mbe = { path = "../ra_mbe", package = "ra_mbe" }
21tt = { path = "../ra_tt", package = "ra_tt" } 21tt = { path = "../ra_tt", package = "ra_tt" }
22hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } 22hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
23test_utils = { path = "../test_utils" } 23test_utils = { path = "../test_utils" }
24ra_prof = { path = "../ra_prof" } 24ra_prof = { path = "../ra_prof" }
25 25
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs
index 7abbf8dca..6d34c671d 100644
--- a/crates/ra_hir/src/db.rs
+++ b/crates/ra_hir/src/db.rs
@@ -3,7 +3,7 @@
3use std::sync::Arc; 3use std::sync::Arc;
4 4
5use ra_db::{salsa, SourceDatabase}; 5use ra_db::{salsa, SourceDatabase};
6use ra_syntax::{ast, Parse, SmolStr, SyntaxNode}; 6use ra_syntax::{ast, SmolStr};
7 7
8use crate::{ 8use crate::{
9 adt::{EnumData, StructData}, 9 adt::{EnumData, StructData},
@@ -19,9 +19,13 @@ use crate::{
19 InferenceResult, Substs, Ty, TypableDef, TypeCtor, 19 InferenceResult, Substs, Ty, TypableDef, TypeCtor,
20 }, 20 },
21 type_alias::TypeAliasData, 21 type_alias::TypeAliasData,
22 AstIdMap, Const, ConstData, Crate, DefWithBody, Enum, ErasedFileAstId, ExprScopes, FnData, 22 Const, ConstData, Crate, DefWithBody, Enum, ExprScopes, FnData, Function, HirFileId, Module,
23 Function, HirFileId, MacroCallLoc, MacroDefId, Module, Static, Struct, StructField, Trait, 23 Static, Struct, StructField, Trait, TypeAlias,
24 TypeAlias, 24};
25
26pub use hir_expand::db::{
27 AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery,
28 ParseMacroQuery,
25}; 29};
26 30
27/// We store all interned things in the single QueryGroup. 31/// We store all interned things in the single QueryGroup.
@@ -32,8 +36,6 @@ use crate::{
32#[salsa::query_group(InternDatabaseStorage)] 36#[salsa::query_group(InternDatabaseStorage)]
33pub trait InternDatabase: SourceDatabase { 37pub trait InternDatabase: SourceDatabase {
34 #[salsa::interned] 38 #[salsa::interned]
35 fn intern_macro(&self, macro_call: MacroCallLoc) -> ids::MacroCallId;
36 #[salsa::interned]
37 fn intern_function(&self, loc: ids::ItemLoc<ast::FnDef>) -> ids::FunctionId; 39 fn intern_function(&self, loc: ids::ItemLoc<ast::FnDef>) -> ids::FunctionId;
38 #[salsa::interned] 40 #[salsa::interned]
39 fn intern_struct(&self, loc: ids::ItemLoc<ast::StructDef>) -> ids::StructId; 41 fn intern_struct(&self, loc: ids::ItemLoc<ast::StructDef>) -> ids::StructId;
@@ -55,38 +57,10 @@ pub trait InternDatabase: SourceDatabase {
55 fn intern_impl(&self, impl_: Impl) -> ids::GlobalImplId; 57 fn intern_impl(&self, impl_: Impl) -> ids::GlobalImplId;
56} 58}
57 59
58/// This database has access to source code, so queries here are not really
59/// incremental.
60#[salsa::query_group(AstDatabaseStorage)]
61pub trait AstDatabase: InternDatabase {
62 #[salsa::invoke(crate::source_id::ast_id_map_query)]
63 fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
64
65 #[salsa::transparent]
66 #[salsa::invoke(crate::source_id::file_item_query)]
67 fn ast_id_to_node(&self, file_id: HirFileId, ast_id: ErasedFileAstId) -> SyntaxNode;
68
69 #[salsa::transparent]
70 #[salsa::invoke(crate::ids::HirFileId::parse_or_expand_query)]
71 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
72
73 #[salsa::invoke(crate::ids::HirFileId::parse_macro_query)]
74 fn parse_macro(&self, macro_file: ids::MacroFile) -> Option<Parse<SyntaxNode>>;
75
76 #[salsa::invoke(crate::ids::macro_def_query)]
77 fn macro_def(&self, macro_id: MacroDefId) -> Option<Arc<mbe::MacroRules>>;
78
79 #[salsa::invoke(crate::ids::macro_arg_query)]
80 fn macro_arg(&self, macro_call: ids::MacroCallId) -> Option<Arc<tt::Subtree>>;
81
82 #[salsa::invoke(crate::ids::macro_expand_query)]
83 fn macro_expand(&self, macro_call: ids::MacroCallId) -> Result<Arc<tt::Subtree>, String>;
84}
85
86// This database uses `AstDatabase` internally, 60// This database uses `AstDatabase` internally,
87#[salsa::query_group(DefDatabaseStorage)] 61#[salsa::query_group(DefDatabaseStorage)]
88#[salsa::requires(AstDatabase)] 62#[salsa::requires(AstDatabase)]
89pub trait DefDatabase: InternDatabase + HirDebugDatabase { 63pub trait DefDatabase: InternDatabase + HirDebugDatabase + AstDatabase {
90 #[salsa::invoke(crate::adt::StructData::struct_data_query)] 64 #[salsa::invoke(crate::adt::StructData::struct_data_query)]
91 fn struct_data(&self, s: Struct) -> Arc<StructData>; 65 fn struct_data(&self, s: Struct) -> Arc<StructData>;
92 66
diff --git a/crates/ra_hir/src/debug.rs b/crates/ra_hir/src/debug.rs
index 48b69000b..4f3e922c3 100644
--- a/crates/ra_hir/src/debug.rs
+++ b/crates/ra_hir/src/debug.rs
@@ -36,12 +36,6 @@ impl Module {
36 } 36 }
37} 37}
38 38
39impl HirFileId {
40 pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ {
41 debug_fn(move |fmt| db.debug_hir_file_id(self, fmt))
42 }
43}
44
45pub trait HirDebugHelper: HirDatabase { 39pub trait HirDebugHelper: HirDatabase {
46 fn crate_name(&self, _krate: CrateId) -> Option<String> { 40 fn crate_name(&self, _krate: CrateId) -> Option<String> {
47 None 41 None
diff --git a/crates/ra_hir/src/expr/lower.rs b/crates/ra_hir/src/expr/lower.rs
index 24733b3de..b3a9a2e6b 100644
--- a/crates/ra_hir/src/expr/lower.rs
+++ b/crates/ra_hir/src/expr/lower.rs
@@ -465,7 +465,7 @@ where
465 465
466 if let Some(path) = e.path().and_then(|path| self.parse_path(path)) { 466 if let Some(path) = e.path().and_then(|path| self.parse_path(path)) {
467 if let Some(def) = self.resolver.resolve_path_as_macro(self.db, &path) { 467 if let Some(def) = self.resolver.resolve_path_as_macro(self.db, &path) {
468 let call_id = MacroCallLoc { def: def.id, ast_id }.id(self.db); 468 let call_id = self.db.intern_macro(MacroCallLoc { def: def.id, ast_id });
469 let file_id = call_id.as_file(MacroFileKind::Expr); 469 let file_id = call_id.as_file(MacroFileKind::Expr);
470 if let Some(node) = self.db.parse_or_expand(file_id) { 470 if let Some(node) = self.db.parse_or_expand(file_id) {
471 if let Some(expr) = ast::Expr::cast(node) { 471 if let Some(expr) = ast::Expr::cast(node) {
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs
index f141206c6..dea288eb7 100644
--- a/crates/ra_hir/src/ids.rs
+++ b/crates/ra_hir/src/ids.rs
@@ -1,168 +1,21 @@
1//! FIXME: write short doc here 1//! hir makes heavy use of ids: integer (u32) handlers to various things. You
2//! can think of id as a pointer (but without a lifetime) or a file descriptor
3//! (but for hir objects).
4//!
5//! This module defines a bunch of ids we are using. The most important ones are
6//! probably `HirFileId` and `DefId`.
2 7
3use std::{ 8use std::hash::{Hash, Hasher};
4 hash::{Hash, Hasher},
5 sync::Arc,
6};
7 9
8use mbe::MacroRules; 10use ra_db::salsa;
9use ra_db::{salsa, FileId}; 11use ra_syntax::{ast, AstNode};
10use ra_prof::profile;
11use ra_syntax::{ast, AstNode, Parse, SyntaxNode};
12 12
13use crate::{ 13use crate::{
14 db::{AstDatabase, InternDatabase}, 14 db::{AstDatabase, InternDatabase},
15 AstId, Crate, FileAstId, Module, Source, 15 AstId, FileAstId, Module, Source,
16}; 16};
17 17
18/// hir makes heavy use of ids: integer (u32) handlers to various things. You 18pub use hir_expand::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile, MacroFileKind};
19/// can think of id as a pointer (but without a lifetime) or a file descriptor
20/// (but for hir objects).
21///
22/// This module defines a bunch of ids we are using. The most important ones are
23/// probably `HirFileId` and `DefId`.
24
25/// Input to the analyzer is a set of files, where each file is identified by
26/// `FileId` and contains source code. However, another source of source code in
27/// Rust are macros: each macro can be thought of as producing a "temporary
28/// file". To assign an id to such a file, we use the id of the macro call that
29/// produced the file. So, a `HirFileId` is either a `FileId` (source code
30/// written by user), or a `MacroCallId` (source code produced by macro).
31///
32/// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
33/// containing the call plus the offset of the macro call in the file. Note that
34/// this is a recursive definition! However, the size_of of `HirFileId` is
35/// finite (because everything bottoms out at the real `FileId`) and small
36/// (`MacroCallId` uses the location interner).
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub struct HirFileId(HirFileIdRepr);
39
40impl HirFileId {
41 /// For macro-expansion files, returns the file original source file the
42 /// expansion originated from.
43 pub fn original_file(self, db: &impl InternDatabase) -> FileId {
44 match self.0 {
45 HirFileIdRepr::File(file_id) => file_id,
46 HirFileIdRepr::Macro(macro_file) => {
47 let loc = macro_file.macro_call_id.loc(db);
48 loc.ast_id.file_id().original_file(db)
49 }
50 }
51 }
52
53 /// Get the crate which the macro lives in, if it is a macro file.
54 pub(crate) fn macro_crate(self, db: &impl AstDatabase) -> Option<Crate> {
55 match self.0 {
56 HirFileIdRepr::File(_) => None,
57 HirFileIdRepr::Macro(macro_file) => {
58 let loc = macro_file.macro_call_id.loc(db);
59 Some(loc.def.krate)
60 }
61 }
62 }
63
64 pub(crate) fn parse_or_expand_query(
65 db: &impl AstDatabase,
66 file_id: HirFileId,
67 ) -> Option<SyntaxNode> {
68 match file_id.0 {
69 HirFileIdRepr::File(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
70 HirFileIdRepr::Macro(macro_file) => {
71 db.parse_macro(macro_file).map(|it| it.syntax_node())
72 }
73 }
74 }
75
76 pub(crate) fn parse_macro_query(
77 db: &impl AstDatabase,
78 macro_file: MacroFile,
79 ) -> Option<Parse<SyntaxNode>> {
80 let _p = profile("parse_macro_query");
81 let macro_call_id = macro_file.macro_call_id;
82 let tt = db
83 .macro_expand(macro_call_id)
84 .map_err(|err| {
85 // Note:
86 // The final goal we would like to make all parse_macro success,
87 // such that the following log will not call anyway.
88 log::warn!("fail on macro_parse: (reason: {})", err,);
89 })
90 .ok()?;
91 match macro_file.macro_file_kind {
92 MacroFileKind::Items => mbe::token_tree_to_items(&tt).ok().map(Parse::to_syntax),
93 MacroFileKind::Expr => mbe::token_tree_to_expr(&tt).ok().map(Parse::to_syntax),
94 }
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99enum HirFileIdRepr {
100 File(FileId),
101 Macro(MacroFile),
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub struct MacroFile {
106 macro_call_id: MacroCallId,
107 macro_file_kind: MacroFileKind,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub(crate) enum MacroFileKind {
112 Items,
113 Expr,
114}
115
116impl From<FileId> for HirFileId {
117 fn from(file_id: FileId) -> HirFileId {
118 HirFileId(HirFileIdRepr::File(file_id))
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub struct MacroDefId {
124 pub(crate) ast_id: AstId<ast::MacroCall>,
125 pub(crate) krate: Crate,
126}
127
128pub(crate) fn macro_def_query(db: &impl AstDatabase, id: MacroDefId) -> Option<Arc<MacroRules>> {
129 let macro_call = id.ast_id.to_node(db);
130 let arg = macro_call.token_tree()?;
131 let (tt, _) = mbe::ast_to_token_tree(&arg).or_else(|| {
132 log::warn!("fail on macro_def to token tree: {:#?}", arg);
133 None
134 })?;
135 let rules = MacroRules::parse(&tt).ok().or_else(|| {
136 log::warn!("fail on macro_def parse: {:#?}", tt);
137 None
138 })?;
139 Some(Arc::new(rules))
140}
141
142pub(crate) fn macro_arg_query(db: &impl AstDatabase, id: MacroCallId) -> Option<Arc<tt::Subtree>> {
143 let loc = id.loc(db);
144 let macro_call = loc.ast_id.to_node(db);
145 let arg = macro_call.token_tree()?;
146 let (tt, _) = mbe::ast_to_token_tree(&arg)?;
147 Some(Arc::new(tt))
148}
149
150pub(crate) fn macro_expand_query(
151 db: &impl AstDatabase,
152 id: MacroCallId,
153) -> Result<Arc<tt::Subtree>, String> {
154 let loc = id.loc(db);
155 let macro_arg = db.macro_arg(id).ok_or("Fail to args in to tt::TokenTree")?;
156
157 let macro_rules = db.macro_def(loc.def).ok_or("Fail to find macro definition")?;
158 let tt = macro_rules.expand(&macro_arg).map_err(|err| format!("{:?}", err))?;
159 // Set a hard limit for the expanded tt
160 let count = tt.count();
161 if count > 65536 {
162 return Err(format!("Total tokens count exceed limit : count = {}", count));
163 }
164 Ok(Arc::new(tt))
165}
166 19
167macro_rules! impl_intern_key { 20macro_rules! impl_intern_key {
168 ($name:ident) => { 21 ($name:ident) => {
@@ -177,35 +30,6 @@ macro_rules! impl_intern_key {
177 }; 30 };
178} 31}
179 32
180/// `MacroCallId` identifies a particular macro invocation, like
181/// `println!("Hello, {}", world)`.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
183pub struct MacroCallId(salsa::InternId);
184impl_intern_key!(MacroCallId);
185
186#[derive(Debug, Clone, PartialEq, Eq, Hash)]
187pub struct MacroCallLoc {
188 pub(crate) def: MacroDefId,
189 pub(crate) ast_id: AstId<ast::MacroCall>,
190}
191
192impl MacroCallId {
193 pub(crate) fn loc(self, db: &impl InternDatabase) -> MacroCallLoc {
194 db.lookup_intern_macro(self)
195 }
196
197 pub(crate) fn as_file(self, kind: MacroFileKind) -> HirFileId {
198 let macro_file = MacroFile { macro_call_id: self, macro_file_kind: kind };
199 HirFileId(HirFileIdRepr::Macro(macro_file))
200 }
201}
202
203impl MacroCallLoc {
204 pub(crate) fn id(self, db: &impl InternDatabase) -> MacroCallId {
205 db.intern_macro(self)
206 }
207}
208
209#[derive(Debug)] 33#[derive(Debug)]
210pub struct ItemLoc<N: AstNode> { 34pub struct ItemLoc<N: AstNode> {
211 pub(crate) module: Module, 35 pub(crate) module: Module,
@@ -244,7 +68,7 @@ impl<'a, DB> LocationCtx<&'a DB> {
244 } 68 }
245} 69}
246 70
247impl<'a, DB: AstDatabase> LocationCtx<&'a DB> { 71impl<'a, DB: AstDatabase + InternDatabase> LocationCtx<&'a DB> {
248 pub(crate) fn to_def<N, DEF>(self, ast: &N) -> DEF 72 pub(crate) fn to_def<N, DEF>(self, ast: &N) -> DEF
249 where 73 where
250 N: AstNode, 74 N: AstNode,
@@ -258,7 +82,7 @@ pub(crate) trait AstItemDef<N: AstNode>: salsa::InternKey + Clone {
258 fn intern(db: &impl InternDatabase, loc: ItemLoc<N>) -> Self; 82 fn intern(db: &impl InternDatabase, loc: ItemLoc<N>) -> Self;
259 fn lookup_intern(self, db: &impl InternDatabase) -> ItemLoc<N>; 83 fn lookup_intern(self, db: &impl InternDatabase) -> ItemLoc<N>;
260 84
261 fn from_ast(ctx: LocationCtx<&impl AstDatabase>, ast: &N) -> Self { 85 fn from_ast(ctx: LocationCtx<&(impl AstDatabase + InternDatabase)>, ast: &N) -> Self {
262 let items = ctx.db.ast_id_map(ctx.file_id); 86 let items = ctx.db.ast_id_map(ctx.file_id);
263 let item_id = items.ast_id(ast); 87 let item_id = items.ast_id(ast);
264 Self::from_ast_id(ctx, item_id) 88 Self::from_ast_id(ctx, item_id)
@@ -267,7 +91,7 @@ pub(crate) trait AstItemDef<N: AstNode>: salsa::InternKey + Clone {
267 let loc = ItemLoc { module: ctx.module, ast_id: AstId::new(ctx.file_id, ast_id) }; 91 let loc = ItemLoc { module: ctx.module, ast_id: AstId::new(ctx.file_id, ast_id) };
268 Self::intern(ctx.db, loc) 92 Self::intern(ctx.db, loc)
269 } 93 }
270 fn source(self, db: &impl AstDatabase) -> Source<N> { 94 fn source(self, db: &(impl AstDatabase + InternDatabase)) -> Source<N> {
271 let loc = self.lookup_intern(db); 95 let loc = self.lookup_intern(db);
272 let ast = loc.ast_id.to_node(db); 96 let ast = loc.ast_id.to_node(db);
273 Source { file_id: loc.ast_id.file_id(), ast } 97 Source { file_id: loc.ast_id.file_id(), ast }
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs
index 9c739f3f1..1a5223680 100644
--- a/crates/ra_hir/src/impl_block.rs
+++ b/crates/ra_hir/src/impl_block.rs
@@ -263,7 +263,7 @@ impl ModuleImplBlocks {
263 { 263 {
264 if let Some(def) = self.module.resolver(db).resolve_path_as_macro(db, &path) 264 if let Some(def) = self.module.resolver(db).resolve_path_as_macro(db, &path)
265 { 265 {
266 let call_id = MacroCallLoc { def: def.id, ast_id }.id(db); 266 let call_id = db.intern_macro(MacroCallLoc { def: def.id, ast_id });
267 let file_id = call_id.as_file(MacroFileKind::Items); 267 let file_id = call_id.as_file(MacroFileKind::Items);
268 if let Some(item_list) = 268 if let Some(item_list) =
269 db.parse_or_expand(file_id).and_then(ast::MacroItems::cast) 269 db.parse_or_expand(file_id).and_then(ast::MacroItems::cast)
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index ca261e8f5..0f2d233bb 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -35,7 +35,6 @@ pub mod mock;
35mod path; 35mod path;
36pub mod source_binder; 36pub mod source_binder;
37 37
38mod source_id;
39mod ids; 38mod ids;
40mod name; 39mod name;
41mod nameres; 40mod nameres;
@@ -60,14 +59,14 @@ pub mod from_source;
60#[cfg(test)] 59#[cfg(test)]
61mod marks; 60mod marks;
62 61
63use crate::{ 62use hir_expand::{
64 ids::MacroFileKind, 63 ast_id_map::{AstIdMap, FileAstId},
65 name::AsName, 64 AstId,
66 resolve::Resolver,
67 source_id::{AstId, FileAstId},
68}; 65};
69 66
70pub use self::{ 67use crate::{ids::MacroFileKind, name::AsName, resolve::Resolver};
68
69pub use crate::{
71 adt::VariantDef, 70 adt::VariantDef,
72 either::Either, 71 either::Either,
73 expr::ExprScopes, 72 expr::ExprScopes,
@@ -80,7 +79,6 @@ pub use self::{
80 path::{Path, PathKind}, 79 path::{Path, PathKind},
81 resolve::ScopeDef, 80 resolve::ScopeDef,
82 source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, 81 source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer},
83 source_id::{AstIdMap, ErasedFileAstId},
84 ty::{ 82 ty::{
85 display::HirDisplay, ApplicationTy, CallableDef, Substs, TraitRef, Ty, TypeCtor, TypeWalk, 83 display::HirDisplay, ApplicationTy, CallableDef, Substs, TraitRef, Ty, TypeCtor, TypeWalk,
86 }, 84 },
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs
index 4f363df36..dc591e8d3 100644
--- a/crates/ra_hir/src/nameres/collector.rs
+++ b/crates/ra_hir/src/nameres/collector.rs
@@ -448,7 +448,7 @@ where
448 ); 448 );
449 449
450 if let Some(def) = resolved_res.resolved_def.get_macros() { 450 if let Some(def) = resolved_res.resolved_def.get_macros() {
451 let call_id = MacroCallLoc { def: def.id, ast_id: *ast_id }.id(self.db); 451 let call_id = self.db.intern_macro(MacroCallLoc { def: def.id, ast_id: *ast_id });
452 resolved.push((*module_id, call_id, def.id)); 452 resolved.push((*module_id, call_id, def.id));
453 res = ReachedFixedPoint::No; 453 res = ReachedFixedPoint::No;
454 return false; 454 return false;
@@ -676,7 +676,8 @@ where
676 // Case 1: macro rules, define a macro in crate-global mutable scope 676 // Case 1: macro rules, define a macro in crate-global mutable scope
677 if is_macro_rules(&mac.path) { 677 if is_macro_rules(&mac.path) {
678 if let Some(name) = &mac.name { 678 if let Some(name) = &mac.name {
679 let macro_id = MacroDefId { ast_id, krate: self.def_collector.def_map.krate }; 679 let macro_id =
680 MacroDefId { ast_id, krate: self.def_collector.def_map.krate.crate_id };
680 let macro_ = MacroDef { id: macro_id }; 681 let macro_ = MacroDef { id: macro_id };
681 self.def_collector.define_macro(self.module_id, name.clone(), macro_, mac.export); 682 self.def_collector.define_macro(self.module_id, name.clone(), macro_, mac.export);
682 } 683 }
@@ -689,7 +690,7 @@ where
689 self.def_collector.def_map[self.module_id].scope.get_legacy_macro(&name) 690 self.def_collector.def_map[self.module_id].scope.get_legacy_macro(&name)
690 }) { 691 }) {
691 let def = macro_def.id; 692 let def = macro_def.id;
692 let macro_call_id = MacroCallLoc { def, ast_id }.id(self.def_collector.db); 693 let macro_call_id = self.def_collector.db.intern_macro(MacroCallLoc { def, ast_id });
693 694
694 self.def_collector.collect_macro_expansion(self.module_id, macro_call_id, def); 695 self.def_collector.collect_macro_expansion(self.module_id, macro_call_id, def);
695 return; 696 return;
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs
index 394617e1a..bbe536bcb 100644
--- a/crates/ra_hir/src/path.rs
+++ b/crates/ra_hir/src/path.rs
@@ -66,7 +66,12 @@ impl Path {
66 mut cb: impl FnMut(Path, &ast::UseTree, bool, Option<Name>), 66 mut cb: impl FnMut(Path, &ast::UseTree, bool, Option<Name>),
67 ) { 67 ) {
68 if let Some(tree) = item_src.ast.use_tree() { 68 if let Some(tree) = item_src.ast.use_tree() {
69 expand_use_tree(None, tree, &|| item_src.file_id.macro_crate(db), &mut cb); 69 expand_use_tree(
70 None,
71 tree,
72 &|| item_src.file_id.macro_crate(db).map(|crate_id| Crate { crate_id }),
73 &mut cb,
74 );
70 } 75 }
71 } 76 }
72 77
@@ -90,7 +95,7 @@ impl Path {
90 /// It correctly handles `$crate` based path from macro call. 95 /// It correctly handles `$crate` based path from macro call.
91 pub fn from_src(source: Source<ast::Path>, db: &impl AstDatabase) -> Option<Path> { 96 pub fn from_src(source: Source<ast::Path>, db: &impl AstDatabase) -> Option<Path> {
92 let file_id = source.file_id; 97 let file_id = source.file_id;
93 Path::parse(source.ast, &|| file_id.macro_crate(db)) 98 Path::parse(source.ast, &|| file_id.macro_crate(db).map(|crate_id| Crate { crate_id }))
94 } 99 }
95 100
96 fn parse(mut path: ast::Path, macro_crate: &impl Fn() -> Option<Crate>) -> Option<Path> { 101 fn parse(mut path: ast::Path, macro_crate: &impl Fn() -> Option<Crate>) -> Option<Path> {
diff --git a/crates/ra_hir/src/source_id.rs b/crates/ra_hir/src/source_id.rs
deleted file mode 100644
index 260b79661..000000000
--- a/crates/ra_hir/src/source_id.rs
+++ /dev/null
@@ -1,73 +0,0 @@
1//! FIXME: write short doc here
2
3use std::{
4 hash::{Hash, Hasher},
5 sync::Arc,
6};
7
8pub use hir_def::ast_id_map::{AstIdMap, ErasedFileAstId, FileAstId};
9use ra_syntax::{AstNode, SyntaxNode};
10
11use crate::{db::AstDatabase, HirFileId};
12
13/// `AstId` points to an AST node in any file.
14///
15/// It is stable across reparses, and can be used as salsa key/value.
16// FIXME: isn't this just a `Source<FileAstId<N>>` ?
17#[derive(Debug)]
18pub(crate) struct AstId<N: AstNode> {
19 file_id: HirFileId,
20 file_ast_id: FileAstId<N>,
21}
22
23impl<N: AstNode> Clone for AstId<N> {
24 fn clone(&self) -> AstId<N> {
25 *self
26 }
27}
28impl<N: AstNode> Copy for AstId<N> {}
29
30impl<N: AstNode> PartialEq for AstId<N> {
31 fn eq(&self, other: &Self) -> bool {
32 (self.file_id, self.file_ast_id) == (other.file_id, other.file_ast_id)
33 }
34}
35impl<N: AstNode> Eq for AstId<N> {}
36impl<N: AstNode> Hash for AstId<N> {
37 fn hash<H: Hasher>(&self, hasher: &mut H) {
38 (self.file_id, self.file_ast_id).hash(hasher);
39 }
40}
41
42impl<N: AstNode> AstId<N> {
43 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
44 AstId { file_id, file_ast_id }
45 }
46
47 pub(crate) fn file_id(&self) -> HirFileId {
48 self.file_id
49 }
50
51 pub(crate) fn to_node(&self, db: &impl AstDatabase) -> N {
52 let syntax_node = db.ast_id_to_node(self.file_id, self.file_ast_id.into());
53 N::cast(syntax_node).unwrap()
54 }
55}
56
57pub(crate) fn ast_id_map_query(db: &impl AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
58 let map = if let Some(node) = db.parse_or_expand(file_id) {
59 AstIdMap::from_source(&node)
60 } else {
61 AstIdMap::default()
62 };
63 Arc::new(map)
64}
65
66pub(crate) fn file_item_query(
67 db: &impl AstDatabase,
68 file_id: HirFileId,
69 ast_id: ErasedFileAstId,
70) -> SyntaxNode {
71 let node = db.parse_or_expand(file_id).unwrap();
72 db.ast_id_map(file_id)[ast_id].to_node(&node)
73}
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
deleted file mode 100644
index 4d4d2cb19..000000000
--- a/crates/ra_hir_def/src/lib.rs
+++ /dev/null
@@ -1,7 +0,0 @@
1//! `ra_hir_def` contains initial "phases" of the compiler. Roughly, everything
2//! before types.
3//!
4//! Note that we are in the process of moving parts of `ra_hir` into
5//! `ra_hir_def`, so this crates doesn't contain a lot at the moment.
6
7pub mod ast_id_map;
diff --git a/crates/ra_hir_def/Cargo.toml b/crates/ra_hir_expand/Cargo.toml
index 7c57d56bd..9bf5b7918 100644
--- a/crates/ra_hir_def/Cargo.toml
+++ b/crates/ra_hir_expand/Cargo.toml
@@ -1,10 +1,15 @@
1[package] 1[package]
2edition = "2018" 2edition = "2018"
3name = "ra_hir_def" 3name = "ra_hir_expand"
4version = "0.1.0" 4version = "0.1.0"
5authors = ["rust-analyzer developers"] 5authors = ["rust-analyzer developers"]
6 6
7[dependencies] 7[dependencies]
8log = "0.4.5"
9
8ra_arena = { path = "../ra_arena" } 10ra_arena = { path = "../ra_arena" }
9ra_db = { path = "../ra_db" } 11ra_db = { path = "../ra_db" }
10ra_syntax = { path = "../ra_syntax" } 12ra_syntax = { path = "../ra_syntax" }
13ra_prof = { path = "../ra_prof" }
14tt = { path = "../ra_tt", package = "ra_tt" }
15mbe = { path = "../ra_mbe", package = "ra_mbe" }
diff --git a/crates/ra_hir_def/src/ast_id_map.rs b/crates/ra_hir_expand/src/ast_id_map.rs
index c3b389102..cb464c3ff 100644
--- a/crates/ra_hir_def/src/ast_id_map.rs
+++ b/crates/ra_hir_expand/src/ast_id_map.rs
@@ -8,11 +8,10 @@
8use std::{ 8use std::{
9 hash::{Hash, Hasher}, 9 hash::{Hash, Hasher},
10 marker::PhantomData, 10 marker::PhantomData,
11 ops,
12}; 11};
13 12
14use ra_arena::{impl_arena_id, Arena, RawId}; 13use ra_arena::{impl_arena_id, Arena, RawId};
15use ra_syntax::{ast, AstNode, SyntaxNode, SyntaxNodePtr}; 14use ra_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr};
16 15
17/// `AstId` points to an AST node in a specific file. 16/// `AstId` points to an AST node in a specific file.
18#[derive(Debug)] 17#[derive(Debug)]
@@ -40,14 +39,8 @@ impl<N: AstNode> Hash for FileAstId<N> {
40 } 39 }
41} 40}
42 41
43impl<N: AstNode> From<FileAstId<N>> for ErasedFileAstId {
44 fn from(id: FileAstId<N>) -> Self {
45 id.raw
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub struct ErasedFileAstId(RawId); 43struct ErasedFileAstId(RawId);
51impl_arena_id!(ErasedFileAstId); 44impl_arena_id!(ErasedFileAstId);
52 45
53/// Maps items' `SyntaxNode`s to `ErasedFileAstId`s and back. 46/// Maps items' `SyntaxNode`s to `ErasedFileAstId`s and back.
@@ -57,7 +50,7 @@ pub struct AstIdMap {
57} 50}
58 51
59impl AstIdMap { 52impl AstIdMap {
60 pub fn from_source(node: &SyntaxNode) -> AstIdMap { 53 pub(crate) fn from_source(node: &SyntaxNode) -> AstIdMap {
61 assert!(node.parent().is_none()); 54 assert!(node.parent().is_none());
62 let mut res = AstIdMap { arena: Arena::default() }; 55 let mut res = AstIdMap { arena: Arena::default() };
63 // By walking the tree in bread-first order we make sure that parents 56 // By walking the tree in bread-first order we make sure that parents
@@ -75,17 +68,23 @@ impl AstIdMap {
75 } 68 }
76 69
77 pub fn ast_id<N: AstNode>(&self, item: &N) -> FileAstId<N> { 70 pub fn ast_id<N: AstNode>(&self, item: &N) -> FileAstId<N> {
78 let ptr = SyntaxNodePtr::new(item.syntax()); 71 let raw = self.erased_ast_id(item.syntax());
79 let raw = match self.arena.iter().find(|(_id, i)| **i == ptr) { 72 FileAstId { raw, _ty: PhantomData }
73 }
74 fn erased_ast_id(&self, item: &SyntaxNode) -> ErasedFileAstId {
75 let ptr = SyntaxNodePtr::new(item);
76 match self.arena.iter().find(|(_id, i)| **i == ptr) {
80 Some((it, _)) => it, 77 Some((it, _)) => it,
81 None => panic!( 78 None => panic!(
82 "Can't find {:?} in AstIdMap:\n{:?}", 79 "Can't find {:?} in AstIdMap:\n{:?}",
83 item.syntax(), 80 item,
84 self.arena.iter().map(|(_id, i)| i).collect::<Vec<_>>(), 81 self.arena.iter().map(|(_id, i)| i).collect::<Vec<_>>(),
85 ), 82 ),
86 }; 83 }
84 }
87 85
88 FileAstId { raw, _ty: PhantomData } 86 pub(crate) fn get<N: AstNode>(&self, id: FileAstId<N>) -> AstPtr<N> {
87 self.arena[id.raw].cast::<N>().unwrap()
89 } 88 }
90 89
91 fn alloc(&mut self, item: &SyntaxNode) -> ErasedFileAstId { 90 fn alloc(&mut self, item: &SyntaxNode) -> ErasedFileAstId {
@@ -93,13 +92,6 @@ impl AstIdMap {
93 } 92 }
94} 93}
95 94
96impl ops::Index<ErasedFileAstId> for AstIdMap {
97 type Output = SyntaxNodePtr;
98 fn index(&self, index: ErasedFileAstId) -> &SyntaxNodePtr {
99 &self.arena[index]
100 }
101}
102
103/// Walks the subtree in bfs order, calling `f` for each node. 95/// Walks the subtree in bfs order, calling `f` for each node.
104fn bfs(node: &SyntaxNode, mut f: impl FnMut(SyntaxNode)) { 96fn bfs(node: &SyntaxNode, mut f: impl FnMut(SyntaxNode)) {
105 let mut curr_layer = vec![node.clone()]; 97 let mut curr_layer = vec![node.clone()];
diff --git a/crates/ra_hir_expand/src/db.rs b/crates/ra_hir_expand/src/db.rs
new file mode 100644
index 000000000..a4ee9a529
--- /dev/null
+++ b/crates/ra_hir_expand/src/db.rs
@@ -0,0 +1,104 @@
1//! Defines database & queries for macro expansion.
2
3use std::sync::Arc;
4
5use mbe::MacroRules;
6use ra_db::{salsa, SourceDatabase};
7use ra_prof::profile;
8use ra_syntax::{AstNode, Parse, SyntaxNode};
9
10use crate::{
11 ast_id_map::AstIdMap, HirFileId, HirFileIdRepr, MacroCallId, MacroCallLoc, MacroDefId,
12 MacroFile, MacroFileKind,
13};
14
15// FIXME: rename to ExpandDatabase
16#[salsa::query_group(AstDatabaseStorage)]
17pub trait AstDatabase: SourceDatabase {
18 fn ast_id_map(&self, file_id: HirFileId) -> Arc<AstIdMap>;
19
20 #[salsa::transparent]
21 fn parse_or_expand(&self, file_id: HirFileId) -> Option<SyntaxNode>;
22
23 #[salsa::interned]
24 fn intern_macro(&self, macro_call: MacroCallLoc) -> MacroCallId;
25 fn macro_arg(&self, id: MacroCallId) -> Option<Arc<tt::Subtree>>;
26 fn macro_def(&self, id: MacroDefId) -> Option<Arc<mbe::MacroRules>>;
27 fn parse_macro(&self, macro_file: MacroFile) -> Option<Parse<SyntaxNode>>;
28 fn macro_expand(&self, macro_call: MacroCallId) -> Result<Arc<tt::Subtree>, String>;
29}
30
31pub(crate) fn ast_id_map(db: &dyn AstDatabase, file_id: HirFileId) -> Arc<AstIdMap> {
32 let map =
33 db.parse_or_expand(file_id).map_or_else(AstIdMap::default, |it| AstIdMap::from_source(&it));
34 Arc::new(map)
35}
36
37pub(crate) fn macro_def(db: &dyn AstDatabase, id: MacroDefId) -> Option<Arc<MacroRules>> {
38 let macro_call = id.ast_id.to_node(db);
39 let arg = macro_call.token_tree()?;
40 let (tt, _) = mbe::ast_to_token_tree(&arg).or_else(|| {
41 log::warn!("fail on macro_def to token tree: {:#?}", arg);
42 None
43 })?;
44 let rules = MacroRules::parse(&tt).ok().or_else(|| {
45 log::warn!("fail on macro_def parse: {:#?}", tt);
46 None
47 })?;
48 Some(Arc::new(rules))
49}
50
51pub(crate) fn macro_arg(db: &dyn AstDatabase, id: MacroCallId) -> Option<Arc<tt::Subtree>> {
52 let loc = db.lookup_intern_macro(id);
53 let macro_call = loc.ast_id.to_node(db);
54 let arg = macro_call.token_tree()?;
55 let (tt, _) = mbe::ast_to_token_tree(&arg)?;
56 Some(Arc::new(tt))
57}
58
59pub(crate) fn macro_expand(
60 db: &dyn AstDatabase,
61 id: MacroCallId,
62) -> Result<Arc<tt::Subtree>, String> {
63 let loc = db.lookup_intern_macro(id);
64 let macro_arg = db.macro_arg(id).ok_or("Fail to args in to tt::TokenTree")?;
65
66 let macro_rules = db.macro_def(loc.def).ok_or("Fail to find macro definition")?;
67 let tt = macro_rules.expand(&macro_arg).map_err(|err| format!("{:?}", err))?;
68 // Set a hard limit for the expanded tt
69 let count = tt.count();
70 if count > 65536 {
71 return Err(format!("Total tokens count exceed limit : count = {}", count));
72 }
73 Ok(Arc::new(tt))
74}
75
76pub(crate) fn parse_or_expand(db: &dyn AstDatabase, file_id: HirFileId) -> Option<SyntaxNode> {
77 match file_id.0 {
78 HirFileIdRepr::FileId(file_id) => Some(db.parse(file_id).tree().syntax().clone()),
79 HirFileIdRepr::MacroFile(macro_file) => {
80 db.parse_macro(macro_file).map(|it| it.syntax_node())
81 }
82 }
83}
84
85pub(crate) fn parse_macro(
86 db: &dyn AstDatabase,
87 macro_file: MacroFile,
88) -> Option<Parse<SyntaxNode>> {
89 let _p = profile("parse_macro_query");
90 let macro_call_id = macro_file.macro_call_id;
91 let tt = db
92 .macro_expand(macro_call_id)
93 .map_err(|err| {
94 // Note:
95 // The final goal we would like to make all parse_macro success,
96 // such that the following log will not call anyway.
97 log::warn!("fail on macro_parse: (reason: {})", err,);
98 })
99 .ok()?;
100 match macro_file.macro_file_kind {
101 MacroFileKind::Items => mbe::token_tree_to_items(&tt).ok().map(Parse::to_syntax),
102 MacroFileKind::Expr => mbe::token_tree_to_expr(&tt).ok().map(Parse::to_syntax),
103 }
104}
diff --git a/crates/ra_hir_expand/src/lib.rs b/crates/ra_hir_expand/src/lib.rs
new file mode 100644
index 000000000..6b3538673
--- /dev/null
+++ b/crates/ra_hir_expand/src/lib.rs
@@ -0,0 +1,161 @@
1//! `ra_hir_expand` deals with macro expansion.
2//!
3//! Specifically, it implements a concept of `MacroFile` -- a file whose syntax
4//! tree originates not from the text of some `FileId`, but from some macro
5//! expansion.
6
7pub mod db;
8pub mod ast_id_map;
9
10use std::hash::{Hash, Hasher};
11
12use ra_db::{salsa, CrateId, FileId};
13use ra_syntax::ast::{self, AstNode};
14
15use crate::{ast_id_map::FileAstId, db::AstDatabase};
16
17/// Input to the analyzer is a set of files, where each file is identified by
18/// `FileId` and contains source code. However, another source of source code in
19/// Rust are macros: each macro can be thought of as producing a "temporary
20/// file". To assign an id to such a file, we use the id of the macro call that
21/// produced the file. So, a `HirFileId` is either a `FileId` (source code
22/// written by user), or a `MacroCallId` (source code produced by macro).
23///
24/// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
25/// containing the call plus the offset of the macro call in the file. Note that
26/// this is a recursive definition! However, the size_of of `HirFileId` is
27/// finite (because everything bottoms out at the real `FileId`) and small
28/// (`MacroCallId` uses the location interner).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub struct HirFileId(HirFileIdRepr);
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33enum HirFileIdRepr {
34 FileId(FileId),
35 MacroFile(MacroFile),
36}
37
38impl From<FileId> for HirFileId {
39 fn from(id: FileId) -> Self {
40 HirFileId(HirFileIdRepr::FileId(id))
41 }
42}
43
44impl From<MacroFile> for HirFileId {
45 fn from(id: MacroFile) -> Self {
46 HirFileId(HirFileIdRepr::MacroFile(id))
47 }
48}
49
50impl HirFileId {
51 /// For macro-expansion files, returns the file original source file the
52 /// expansion originated from.
53 pub fn original_file(self, db: &dyn AstDatabase) -> FileId {
54 match self.0 {
55 HirFileIdRepr::FileId(file_id) => file_id,
56 HirFileIdRepr::MacroFile(macro_file) => {
57 let loc = db.lookup_intern_macro(macro_file.macro_call_id);
58 loc.ast_id.file_id().original_file(db)
59 }
60 }
61 }
62
63 /// Get the crate which the macro lives in, if it is a macro file.
64 pub fn macro_crate(self, db: &dyn AstDatabase) -> Option<CrateId> {
65 match self.0 {
66 HirFileIdRepr::FileId(_) => None,
67 HirFileIdRepr::MacroFile(macro_file) => {
68 let loc = db.lookup_intern_macro(macro_file.macro_call_id);
69 Some(loc.def.krate)
70 }
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub struct MacroFile {
77 macro_call_id: MacroCallId,
78 macro_file_kind: MacroFileKind,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum MacroFileKind {
83 Items,
84 Expr,
85}
86
87/// `MacroCallId` identifies a particular macro invocation, like
88/// `println!("Hello, {}", world)`.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub struct MacroCallId(salsa::InternId);
91impl salsa::InternKey for MacroCallId {
92 fn from_intern_id(v: salsa::InternId) -> Self {
93 MacroCallId(v)
94 }
95 fn as_intern_id(&self) -> salsa::InternId {
96 self.0
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub struct MacroDefId {
102 pub krate: CrateId,
103 pub ast_id: AstId<ast::MacroCall>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Hash)]
107pub struct MacroCallLoc {
108 pub def: MacroDefId,
109 pub ast_id: AstId<ast::MacroCall>,
110}
111
112impl MacroCallId {
113 pub fn as_file(self, kind: MacroFileKind) -> HirFileId {
114 let macro_file = MacroFile { macro_call_id: self, macro_file_kind: kind };
115 macro_file.into()
116 }
117}
118
119/// `AstId` points to an AST node in any file.
120///
121/// It is stable across reparses, and can be used as salsa key/value.
122// FIXME: isn't this just a `Source<FileAstId<N>>` ?
123#[derive(Debug)]
124pub struct AstId<N: AstNode> {
125 file_id: HirFileId,
126 file_ast_id: FileAstId<N>,
127}
128
129impl<N: AstNode> Clone for AstId<N> {
130 fn clone(&self) -> AstId<N> {
131 *self
132 }
133}
134impl<N: AstNode> Copy for AstId<N> {}
135
136impl<N: AstNode> PartialEq for AstId<N> {
137 fn eq(&self, other: &Self) -> bool {
138 (self.file_id, self.file_ast_id) == (other.file_id, other.file_ast_id)
139 }
140}
141impl<N: AstNode> Eq for AstId<N> {}
142impl<N: AstNode> Hash for AstId<N> {
143 fn hash<H: Hasher>(&self, hasher: &mut H) {
144 (self.file_id, self.file_ast_id).hash(hasher);
145 }
146}
147
148impl<N: AstNode> AstId<N> {
149 pub fn new(file_id: HirFileId, file_ast_id: FileAstId<N>) -> AstId<N> {
150 AstId { file_id, file_ast_id }
151 }
152
153 pub fn file_id(&self) -> HirFileId {
154 self.file_id
155 }
156
157 pub fn to_node(&self, db: &dyn AstDatabase) -> N {
158 let root = db.parse_or_expand(self.file_id).unwrap();
159 db.ast_id_map(self.file_id).get(self.file_ast_id).to_node(&root)
160 }
161}
diff --git a/crates/ra_ide_api/Cargo.toml b/crates/ra_ide_api/Cargo.toml
index f66f0a6ba..bf6ef12f3 100644
--- a/crates/ra_ide_api/Cargo.toml
+++ b/crates/ra_ide_api/Cargo.toml
@@ -27,10 +27,13 @@ ra_db = { path = "../ra_db" }
27ra_cfg = { path = "../ra_cfg" } 27ra_cfg = { path = "../ra_cfg" }
28ra_fmt = { path = "../ra_fmt" } 28ra_fmt = { path = "../ra_fmt" }
29ra_prof = { path = "../ra_prof" } 29ra_prof = { path = "../ra_prof" }
30hir = { path = "../ra_hir", package = "ra_hir" }
31test_utils = { path = "../test_utils" } 30test_utils = { path = "../test_utils" }
32ra_assists = { path = "../ra_assists" } 31ra_assists = { path = "../ra_assists" }
33 32
33# ra_ide_api should depend only on the top-level `hir` package. if you need
34# something from some `hir_xxx` subpackage, reexport the API via `hir`.
35hir = { path = "../ra_hir", package = "ra_hir" }
36
34[dev-dependencies] 37[dev-dependencies]
35insta = "0.12.0" 38insta = "0.12.0"
36 39