]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir_expand/src/lib.rs
Replace `ra_hir_expand::either` with crate
[rust.git] / crates / ra_hir_expand / src / lib.rs
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
7 pub mod db;
8 pub mod ast_id_map;
9 pub mod name;
10 pub mod hygiene;
11 pub mod diagnostics;
12 pub mod builtin_macro;
13 pub mod quote;
14
15 use std::hash::Hash;
16 use std::sync::Arc;
17
18 use ra_db::{salsa, CrateId, FileId};
19 use ra_syntax::{
20     algo,
21     ast::{self, AstNode},
22     SyntaxNode, SyntaxToken, TextUnit,
23 };
24
25 use crate::ast_id_map::FileAstId;
26 use crate::builtin_macro::BuiltinFnLikeExpander;
27
28 #[cfg(test)]
29 mod test_db;
30
31 /// Input to the analyzer is a set of files, where each file is identified by
32 /// `FileId` and contains source code. However, another source of source code in
33 /// Rust are macros: each macro can be thought of as producing a "temporary
34 /// file". To assign an id to such a file, we use the id of the macro call that
35 /// produced the file. So, a `HirFileId` is either a `FileId` (source code
36 /// written by user), or a `MacroCallId` (source code produced by macro).
37 ///
38 /// What is a `MacroCallId`? Simplifying, it's a `HirFileId` of a file
39 /// containing the call plus the offset of the macro call in the file. Note that
40 /// this is a recursive definition! However, the size_of of `HirFileId` is
41 /// finite (because everything bottoms out at the real `FileId`) and small
42 /// (`MacroCallId` uses the location interner).
43 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44 pub struct HirFileId(HirFileIdRepr);
45
46 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47 enum HirFileIdRepr {
48     FileId(FileId),
49     MacroFile(MacroFile),
50 }
51
52 impl From<FileId> for HirFileId {
53     fn from(id: FileId) -> Self {
54         HirFileId(HirFileIdRepr::FileId(id))
55     }
56 }
57
58 impl From<MacroFile> for HirFileId {
59     fn from(id: MacroFile) -> Self {
60         HirFileId(HirFileIdRepr::MacroFile(id))
61     }
62 }
63
64 impl HirFileId {
65     /// For macro-expansion files, returns the file original source file the
66     /// expansion originated from.
67     pub fn original_file(self, db: &dyn db::AstDatabase) -> FileId {
68         match self.0 {
69             HirFileIdRepr::FileId(file_id) => file_id,
70             HirFileIdRepr::MacroFile(macro_file) => {
71                 let loc = db.lookup_intern_macro(macro_file.macro_call_id);
72                 loc.ast_id.file_id.original_file(db)
73             }
74         }
75     }
76
77     /// Return expansion information if it is a macro-expansion file
78     pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
79         match self.0 {
80             HirFileIdRepr::FileId(_) => None,
81             HirFileIdRepr::MacroFile(macro_file) => {
82                 let loc: MacroCallLoc = db.lookup_intern_macro(macro_file.macro_call_id);
83
84                 let arg_tt = loc.ast_id.to_node(db).token_tree()?;
85                 let def_tt = loc.def.ast_id.to_node(db).token_tree()?;
86
87                 let macro_def = db.macro_def(loc.def)?;
88                 let (parse, exp_map) = db.parse_macro(macro_file)?;
89                 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
90
91                 Some(ExpansionInfo {
92                     expanded: InFile::new(self, parse.syntax_node()),
93                     arg: InFile::new(loc.ast_id.file_id, arg_tt),
94                     def: InFile::new(loc.ast_id.file_id, def_tt),
95                     macro_arg,
96                     macro_def,
97                     exp_map,
98                 })
99             }
100         }
101     }
102 }
103
104 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105 pub struct MacroFile {
106     macro_call_id: MacroCallId,
107     macro_file_kind: MacroFileKind,
108 }
109
110 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111 pub enum MacroFileKind {
112     Items,
113     Expr,
114     Statements,
115 }
116
117 /// `MacroCallId` identifies a particular macro invocation, like
118 /// `println!("Hello, {}", world)`.
119 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120 pub struct MacroCallId(salsa::InternId);
121 impl salsa::InternKey for MacroCallId {
122     fn from_intern_id(v: salsa::InternId) -> Self {
123         MacroCallId(v)
124     }
125     fn as_intern_id(&self) -> salsa::InternId {
126         self.0
127     }
128 }
129
130 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131 pub struct MacroDefId {
132     pub krate: CrateId,
133     pub ast_id: AstId<ast::MacroCall>,
134     pub kind: MacroDefKind,
135 }
136
137 impl MacroDefId {
138     pub fn as_call_id(
139         self,
140         db: &dyn db::AstDatabase,
141         ast_id: AstId<ast::MacroCall>,
142     ) -> MacroCallId {
143         db.intern_macro(MacroCallLoc { def: self, ast_id })
144     }
145 }
146
147 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148 pub enum MacroDefKind {
149     Declarative,
150     BuiltIn(BuiltinFnLikeExpander),
151 }
152
153 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
154 pub struct MacroCallLoc {
155     pub(crate) def: MacroDefId,
156     pub(crate) ast_id: AstId<ast::MacroCall>,
157 }
158
159 impl MacroCallId {
160     pub fn as_file(self, kind: MacroFileKind) -> HirFileId {
161         let macro_file = MacroFile { macro_call_id: self, macro_file_kind: kind };
162         macro_file.into()
163     }
164 }
165
166 /// ExpansionInfo mainly describes how to map text range between src and expanded macro
167 #[derive(Debug, Clone, PartialEq, Eq)]
168 pub struct ExpansionInfo {
169     expanded: InFile<SyntaxNode>,
170     arg: InFile<ast::TokenTree>,
171     def: InFile<ast::TokenTree>,
172
173     macro_def: Arc<(db::TokenExpander, mbe::TokenMap)>,
174     macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
175     exp_map: Arc<mbe::TokenMap>,
176 }
177
178 impl ExpansionInfo {
179     pub fn map_token_down(&self, token: InFile<&SyntaxToken>) -> Option<InFile<SyntaxToken>> {
180         assert_eq!(token.file_id, self.arg.file_id);
181         let range =
182             token.value.text_range().checked_sub(self.arg.value.syntax().text_range().start())?;
183         let token_id = self.macro_arg.1.token_by_range(range)?;
184         let token_id = self.macro_def.0.map_id_down(token_id);
185
186         let range = self.exp_map.range_by_token(token_id)?;
187
188         let token = algo::find_covering_element(&self.expanded.value, range).into_token()?;
189
190         Some(self.expanded.with_value(token))
191     }
192
193     pub fn map_token_up(&self, token: InFile<&SyntaxToken>) -> Option<InFile<SyntaxToken>> {
194         let token_id = self.exp_map.token_by_range(token.value.text_range())?;
195
196         let (token_id, origin) = self.macro_def.0.map_id_up(token_id);
197         let (token_map, tt) = match origin {
198             mbe::Origin::Call => (&self.macro_arg.1, &self.arg),
199             mbe::Origin::Def => (&self.macro_def.1, &self.def),
200         };
201
202         let range = token_map.range_by_token(token_id)?;
203         let token = algo::find_covering_element(
204             tt.value.syntax(),
205             range + tt.value.syntax().text_range().start(),
206         )
207         .into_token()?;
208         Some(tt.with_value(token))
209     }
210 }
211
212 /// `AstId` points to an AST node in any file.
213 ///
214 /// It is stable across reparses, and can be used as salsa key/value.
215 // FIXME: isn't this just a `Source<FileAstId<N>>` ?
216 pub type AstId<N> = InFile<FileAstId<N>>;
217
218 impl<N: AstNode> AstId<N> {
219     pub fn to_node(&self, db: &dyn db::AstDatabase) -> N {
220         let root = db.parse_or_expand(self.file_id).unwrap();
221         db.ast_id_map(self.file_id).get(self.value).to_node(&root)
222     }
223 }
224
225 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
226 ///
227 /// Typical usages are:
228 ///
229 /// * `InFile<SyntaxNode>` -- syntax node in a file
230 /// * `InFile<ast::FnDef>` -- ast node in a file
231 /// * `InFile<TextUnit>` -- offset in a file
232 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
233 pub struct InFile<T> {
234     pub file_id: HirFileId,
235     pub value: T,
236 }
237
238 impl<T> InFile<T> {
239     pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
240         InFile { file_id, value }
241     }
242
243     // Similarly, naming here is stupid...
244     pub fn with_value<U>(&self, value: U) -> InFile<U> {
245         InFile::new(self.file_id, value)
246     }
247
248     pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
249         InFile::new(self.file_id, f(self.value))
250     }
251     pub fn as_ref(&self) -> InFile<&T> {
252         self.with_value(&self.value)
253     }
254     pub fn file_syntax(&self, db: &impl db::AstDatabase) -> SyntaxNode {
255         db.parse_or_expand(self.file_id).expect("source created from invalid file")
256     }
257 }