1 //! This modules handles hygiene information.
3 //! Specifically, `ast` + `Hygiene` allows you to create a `Name`. Note that, at
4 //! this moment, this is horribly incomplete and handles only `$crate`.
12 ast::{self, HasDocComments},
13 AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize,
17 db::{self, AstDatabase},
20 HirFileId, HirFileIdRepr, InFile, MacroCallKind, MacroCallLoc, MacroDefKind, MacroFile,
23 #[derive(Clone, Debug)]
25 frames: Option<HygieneFrames>,
29 pub fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Hygiene {
30 Hygiene { frames: Some(HygieneFrames::new(db, file_id)) }
33 pub fn new_unhygienic() -> Hygiene {
34 Hygiene { frames: None }
37 // FIXME: this should just return name
38 pub fn name_ref_to_name(
41 name_ref: ast::NameRef,
42 ) -> Either<Name, CrateId> {
43 if let Some(frames) = &self.frames {
44 if name_ref.text() == "$crate" {
45 if let Some(krate) = frames.root_crate(db, name_ref.syntax()) {
46 return Either::Right(krate);
51 Either::Left(name_ref.as_name())
54 pub fn local_inner_macros(&self, db: &dyn AstDatabase, path: ast::Path) -> Option<CrateId> {
55 let mut token = path.syntax().first_token()?.text_range();
56 let frames = self.frames.as_ref()?;
57 let mut current = &frames.0;
60 let (mapped, origin) = current.expansion.as_ref()?.map_ident_up(db, token)?;
61 if origin == Origin::Def {
62 return if current.local_inner {
63 frames.root_crate(db, path.syntax())
68 current = current.call_site.as_ref()?;
74 #[derive(Clone, Debug)]
75 struct HygieneFrames(Arc<HygieneFrame>);
77 #[derive(Clone, Debug, Eq, PartialEq)]
78 pub struct HygieneFrame {
79 expansion: Option<HygieneInfo>,
81 // Indicate this is a local inner macro
83 krate: Option<CrateId>,
85 call_site: Option<Arc<HygieneFrame>>,
86 def_site: Option<Arc<HygieneFrame>>,
90 fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Self {
91 // Note that this intentionally avoids the `hygiene_frame` query to avoid blowing up memory
92 // usage. The query is only helpful for nested `HygieneFrame`s as it avoids redundant work.
93 HygieneFrames(Arc::new(HygieneFrame::new(db, file_id)))
96 fn root_crate(&self, db: &dyn AstDatabase, node: &SyntaxNode) -> Option<CrateId> {
97 let mut token = node.first_token()?.text_range();
98 let mut result = self.0.krate;
99 let mut current = self.0.clone();
101 while let Some((mapped, origin)) =
102 current.expansion.as_ref().and_then(|it| it.map_ident_up(db, token))
104 result = current.krate;
106 let site = match origin {
107 Origin::Def => ¤t.def_site,
108 Origin::Call => ¤t.call_site,
111 let site = match site {
116 current = site.clone();
117 token = mapped.value;
124 #[derive(Debug, Clone, PartialEq, Eq)]
127 /// The start offset of the `macro_rules!` arguments or attribute input.
128 attr_input_or_mac_def_start: Option<InFile<TextSize>>,
130 macro_def: Arc<TokenExpander>,
131 macro_arg: Arc<(tt::Subtree, mbe::TokenMap, fixup::SyntaxFixupUndoInfo)>,
132 macro_arg_shift: mbe::Shift,
133 exp_map: Arc<mbe::TokenMap>,
139 db: &dyn AstDatabase,
141 ) -> Option<(InFile<TextRange>, Origin)> {
142 let token_id = self.exp_map.token_by_range(token)?;
143 let (mut token_id, origin) = self.macro_def.map_id_up(token_id);
145 let loc = db.lookup_intern_macro_call(self.file.macro_call_id);
147 let (token_map, tt) = match &loc.kind {
148 MacroCallKind::Attr { attr_args, .. } => match self.macro_arg_shift.unshift(token_id) {
150 token_id = unshifted;
151 (&attr_args.1, self.attr_input_or_mac_def_start?)
155 InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
159 mbe::Origin::Call => (
161 InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
163 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def_start) {
164 (TokenExpander::DeclarativeMacro { def_site_token_map, .. }, Some(tt)) => {
165 (def_site_token_map, *tt)
167 _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
172 let range = token_map.first_range_by_token(token_id, SyntaxKind::IDENT)?;
173 Some((tt.with_value(range + tt.value), origin))
177 fn make_hygiene_info(
178 db: &dyn AstDatabase,
179 macro_file: MacroFile,
181 ) -> Option<HygieneInfo> {
182 let def = loc.def.ast_id().left().and_then(|id| {
183 let def_tt = match id.to_node(db) {
184 ast::Macro::MacroRules(mac) => mac.token_tree()?,
185 ast::Macro::MacroDef(mac) => mac.body()?,
187 Some(InFile::new(id.file_id, def_tt))
189 let attr_input_or_mac_def = def.or_else(|| match loc.kind {
190 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
193 .doc_comments_and_attrs()
194 .nth(invoc_attr_index as usize)
195 .and_then(Either::left)?
197 Some(InFile::new(ast_id.file_id, tt))
202 let macro_def = db.macro_def(loc.def).ok()?;
203 let (_, exp_map) = db.parse_macro_expansion(macro_file).value?;
204 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
208 attr_input_or_mac_def_start: attr_input_or_mac_def
209 .map(|it| it.map(|tt| tt.syntax().text_range().start())),
210 macro_arg_shift: mbe::Shift::new(¯o_arg.0),
218 pub(crate) fn new(db: &dyn AstDatabase, file_id: HirFileId) -> HygieneFrame {
219 let (info, krate, local_inner) = match file_id.0 {
220 HirFileIdRepr::FileId(_) => (None, None, false),
221 HirFileIdRepr::MacroFile(macro_file) => {
222 let loc = db.lookup_intern_macro_call(macro_file.macro_call_id);
224 make_hygiene_info(db, macro_file, &loc).map(|info| (loc.kind.file_id(), info));
226 MacroDefKind::Declarative(_) => {
227 (info, Some(loc.def.krate), loc.def.local_inner)
229 MacroDefKind::BuiltIn(..) => (info, Some(loc.def.krate), false),
230 MacroDefKind::BuiltInAttr(..) => (info, None, false),
231 MacroDefKind::BuiltInDerive(..) => (info, None, false),
232 MacroDefKind::BuiltInEager(..) => (info, None, false),
233 MacroDefKind::ProcMacro(..) => (info, None, false),
238 let (calling_file, info) = match info {
240 return HygieneFrame {
251 let def_site = info.attr_input_or_mac_def_start.map(|it| db.hygiene_frame(it.file_id));
252 let call_site = Some(db.hygiene_frame(calling_file));
254 HygieneFrame { expansion: Some(info), local_inner, krate, call_site, def_site }