1 //! `ra_hir_expand` deals with macro expansion.
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
12 pub mod builtin_macro;
18 use ra_db::{salsa, CrateId, FileId};
22 SyntaxNode, SyntaxToken, TextUnit,
25 use crate::ast_id_map::FileAstId;
26 use crate::builtin_macro::BuiltinFnLikeExpander;
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).
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);
46 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52 impl From<FileId> for HirFileId {
53 fn from(id: FileId) -> Self {
54 HirFileId(HirFileIdRepr::FileId(id))
58 impl From<MacroFile> for HirFileId {
59 fn from(id: MacroFile) -> Self {
60 HirFileId(HirFileIdRepr::MacroFile(id))
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 {
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)
77 /// Return expansion information if it is a macro-expansion file
78 pub fn expansion_info(self, db: &dyn db::AstDatabase) -> Option<ExpansionInfo> {
80 HirFileIdRepr::FileId(_) => None,
81 HirFileIdRepr::MacroFile(macro_file) => {
82 let loc: MacroCallLoc = db.lookup_intern_macro(macro_file.macro_call_id);
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()?;
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)?;
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),
104 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105 pub struct MacroFile {
106 macro_call_id: MacroCallId,
107 macro_file_kind: MacroFileKind,
110 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111 pub enum MacroFileKind {
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 {
125 fn as_intern_id(&self) -> salsa::InternId {
130 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131 pub struct MacroDefId {
133 pub ast_id: AstId<ast::MacroCall>,
134 pub kind: MacroDefKind,
140 db: &dyn db::AstDatabase,
141 ast_id: AstId<ast::MacroCall>,
143 db.intern_macro(MacroCallLoc { def: self, ast_id })
147 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148 pub enum MacroDefKind {
150 BuiltIn(BuiltinFnLikeExpander),
153 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
154 pub struct MacroCallLoc {
155 pub(crate) def: MacroDefId,
156 pub(crate) ast_id: AstId<ast::MacroCall>,
160 pub fn as_file(self, kind: MacroFileKind) -> HirFileId {
161 let macro_file = MacroFile { macro_call_id: self, macro_file_kind: kind };
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>,
173 macro_def: Arc<(db::TokenExpander, mbe::TokenMap)>,
174 macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
175 exp_map: Arc<mbe::TokenMap>,
179 pub fn map_token_down(&self, token: InFile<&SyntaxToken>) -> Option<InFile<SyntaxToken>> {
180 assert_eq!(token.file_id, self.arg.file_id);
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);
186 let range = self.exp_map.range_by_token(token_id)?;
188 let token = algo::find_covering_element(&self.expanded.value, range).into_token()?;
190 Some(self.expanded.with_value(token))
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())?;
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),
202 let range = token_map.range_by_token(token_id)?;
203 let token = algo::find_covering_element(
205 range + tt.value.syntax().text_range().start(),
208 Some(tt.with_value(token))
212 /// `AstId` points to an AST node in any file.
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>>;
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)
225 /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
227 /// Typical usages are:
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,
239 pub fn new(file_id: HirFileId, value: T) -> InFile<T> {
240 InFile { file_id, value }
243 // Similarly, naming here is stupid...
244 pub fn with_value<U>(&self, value: U) -> InFile<U> {
245 InFile::new(self.file_id, value)
248 pub fn map<F: FnOnce(T) -> U, U>(self, f: F) -> InFile<U> {
249 InFile::new(self.file_id, f(self.value))
251 pub fn as_ref(&self) -> InFile<&T> {
252 self.with_value(&self.value)
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")