]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/hygiene.rs
5b3ccdeb60577a84a1cbd98e4088cc948817227b
[rust.git] / crates / hir_expand / src / hygiene.rs
1 //! This modules handles hygiene information.
2 //!
3 //! Specifically, `ast` + `Hygiene` allows you to create a `Name`. Note that, at
4 //! this moment, this is horribly incomplete and handles only `$crate`.
5 use std::sync::Arc;
6
7 use base_db::CrateId;
8 use db::TokenExpander;
9 use either::Either;
10 use mbe::Origin;
11 use syntax::{
12     ast::{self, HasAttrs},
13     AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize,
14 };
15
16 use crate::{
17     db::{self, AstDatabase},
18     name::{AsName, Name},
19     HirFileId, HirFileIdRepr, InFile, MacroCallKind, MacroCallLoc, MacroDefKind, MacroFile,
20 };
21
22 #[derive(Clone, Debug)]
23 pub struct Hygiene {
24     frames: Option<HygieneFrames>,
25 }
26
27 impl Hygiene {
28     pub fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Hygiene {
29         Hygiene { frames: Some(HygieneFrames::new(db, file_id)) }
30     }
31
32     pub fn new_unhygienic() -> Hygiene {
33         Hygiene { frames: None }
34     }
35
36     // FIXME: this should just return name
37     pub fn name_ref_to_name(
38         &self,
39         db: &dyn AstDatabase,
40         name_ref: ast::NameRef,
41     ) -> Either<Name, CrateId> {
42         if let Some(frames) = &self.frames {
43             if name_ref.text() == "$crate" {
44                 if let Some(krate) = frames.root_crate(db, name_ref.syntax()) {
45                     return Either::Right(krate);
46                 }
47             }
48         }
49
50         Either::Left(name_ref.as_name())
51     }
52
53     pub fn local_inner_macros(&self, db: &dyn AstDatabase, path: ast::Path) -> Option<CrateId> {
54         let mut token = path.syntax().first_token()?.text_range();
55         let frames = self.frames.as_ref()?;
56         let mut current = &frames.0;
57
58         loop {
59             let (mapped, origin) = current.expansion.as_ref()?.map_ident_up(db, token)?;
60             if origin == Origin::Def {
61                 return if current.local_inner {
62                     frames.root_crate(db, path.syntax())
63                 } else {
64                     None
65                 };
66             }
67             current = current.call_site.as_ref()?;
68             token = mapped.value;
69         }
70     }
71 }
72
73 #[derive(Clone, Debug)]
74 struct HygieneFrames(Arc<HygieneFrame>);
75
76 #[derive(Clone, Debug, Eq, PartialEq)]
77 pub struct HygieneFrame {
78     expansion: Option<HygieneInfo>,
79
80     // Indicate this is a local inner macro
81     local_inner: bool,
82     krate: Option<CrateId>,
83
84     call_site: Option<Arc<HygieneFrame>>,
85     def_site: Option<Arc<HygieneFrame>>,
86 }
87
88 impl HygieneFrames {
89     fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Self {
90         // Note that this intentionally avoids the `hygiene_frame` query to avoid blowing up memory
91         // usage. The query is only helpful for nested `HygieneFrame`s as it avoids redundant work.
92         HygieneFrames(Arc::new(HygieneFrame::new(db, file_id)))
93     }
94
95     fn root_crate(&self, db: &dyn AstDatabase, node: &SyntaxNode) -> Option<CrateId> {
96         let mut token = node.first_token()?.text_range();
97         let mut result = self.0.krate;
98         let mut current = self.0.clone();
99
100         while let Some((mapped, origin)) =
101             current.expansion.as_ref().and_then(|it| it.map_ident_up(db, token))
102         {
103             result = current.krate;
104
105             let site = match origin {
106                 Origin::Def => &current.def_site,
107                 Origin::Call => &current.call_site,
108             };
109
110             let site = match site {
111                 None => break,
112                 Some(it) => it,
113             };
114
115             current = site.clone();
116             token = mapped.value;
117         }
118
119         result
120     }
121 }
122
123 #[derive(Debug, Clone, PartialEq, Eq)]
124 struct HygieneInfo {
125     file: MacroFile,
126     /// The start offset of the `macro_rules!` arguments or attribute input.
127     attr_input_or_mac_def_start: Option<InFile<TextSize>>,
128
129     macro_def: Arc<TokenExpander>,
130     macro_arg: Arc<(tt::Subtree, mbe::TokenMap)>,
131     macro_arg_shift: mbe::Shift,
132     exp_map: Arc<mbe::TokenMap>,
133 }
134
135 impl HygieneInfo {
136     fn map_ident_up(
137         &self,
138         db: &dyn AstDatabase,
139         token: TextRange,
140     ) -> Option<(InFile<TextRange>, Origin)> {
141         let token_id = self.exp_map.token_by_range(token)?;
142         let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
143
144         let loc = db.lookup_intern_macro(self.file.macro_call_id);
145
146         let (token_map, tt) = match &loc.kind {
147             MacroCallKind::Attr { attr_args, .. } => match self.macro_arg_shift.unshift(token_id) {
148                 Some(unshifted) => {
149                     token_id = unshifted;
150                     (&attr_args.1, self.attr_input_or_mac_def_start?)
151                 }
152                 None => (
153                     &self.macro_arg.1,
154                     InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
155                 ),
156             },
157             _ => match origin {
158                 mbe::Origin::Call => (
159                     &self.macro_arg.1,
160                     InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
161                 ),
162                 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def_start) {
163                     (
164                         TokenExpander::MacroDef { def_site_token_map, .. }
165                         | TokenExpander::MacroRules { def_site_token_map, .. },
166                         Some(tt),
167                     ) => (def_site_token_map, *tt),
168                     _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
169                 },
170             },
171         };
172
173         let range = token_map.first_range_by_token(token_id, SyntaxKind::IDENT)?;
174         Some((tt.with_value(range + tt.value), origin))
175     }
176 }
177
178 fn make_hygiene_info(
179     db: &dyn AstDatabase,
180     macro_file: MacroFile,
181     loc: &MacroCallLoc,
182 ) -> Option<HygieneInfo> {
183     let def = loc.def.ast_id().left().and_then(|id| {
184         let def_tt = match id.to_node(db) {
185             ast::Macro::MacroRules(mac) => mac.token_tree()?,
186             ast::Macro::MacroDef(mac) => mac.body()?,
187         };
188         Some(InFile::new(id.file_id, def_tt))
189     });
190     let attr_input_or_mac_def = def.or_else(|| match loc.kind {
191         MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
192             let tt = ast_id.to_node(db).attrs().nth(invoc_attr_index as usize)?.token_tree()?;
193             Some(InFile::new(ast_id.file_id, tt))
194         }
195         _ => None,
196     });
197
198     let macro_def = db.macro_def(loc.def)?;
199     let (_, exp_map) = db.parse_macro_expansion(macro_file).value?;
200     let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
201
202     Some(HygieneInfo {
203         file: macro_file,
204         attr_input_or_mac_def_start: attr_input_or_mac_def
205             .map(|it| it.map(|tt| tt.syntax().text_range().start())),
206         macro_arg_shift: mbe::Shift::new(&macro_arg.0),
207         macro_arg,
208         macro_def,
209         exp_map,
210     })
211 }
212
213 impl HygieneFrame {
214     pub(crate) fn new(db: &dyn AstDatabase, file_id: HirFileId) -> HygieneFrame {
215         let (info, krate, local_inner) = match file_id.0 {
216             HirFileIdRepr::FileId(_) => (None, None, false),
217             HirFileIdRepr::MacroFile(macro_file) => {
218                 let loc = db.lookup_intern_macro(macro_file.macro_call_id);
219                 let info =
220                     make_hygiene_info(db, macro_file, &loc).map(|info| (loc.kind.file_id(), info));
221                 match loc.def.kind {
222                     MacroDefKind::Declarative(_) => {
223                         (info, Some(loc.def.krate), loc.def.local_inner)
224                     }
225                     MacroDefKind::BuiltIn(..) => (info, Some(loc.def.krate), false),
226                     MacroDefKind::BuiltInAttr(..) => (info, None, false),
227                     MacroDefKind::BuiltInDerive(..) => (info, None, false),
228                     MacroDefKind::BuiltInEager(..) => (info, None, false),
229                     MacroDefKind::ProcMacro(..) => (info, None, false),
230                 }
231             }
232         };
233
234         let (calling_file, info) = match info {
235             None => {
236                 return HygieneFrame {
237                     expansion: None,
238                     local_inner,
239                     krate,
240                     call_site: None,
241                     def_site: None,
242                 };
243             }
244             Some(it) => it,
245         };
246
247         let def_site = info.attr_input_or_mac_def_start.map(|it| db.hygiene_frame(it.file_id));
248         let call_site = Some(db.hygiene_frame(calling_file));
249
250         HygieneFrame { expansion: Some(info), local_inner, krate, call_site, def_site }
251     }
252 }