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, HasAttrs},
13 AstNode, SyntaxKind, SyntaxNode, TextRange, TextSize,
17 db::{self, AstDatabase},
19 HirFileId, HirFileIdRepr, InFile, MacroCallKind, MacroCallLoc, MacroDefKind, MacroFile,
22 #[derive(Clone, Debug)]
24 frames: Option<HygieneFrames>,
28 pub fn new(db: &dyn AstDatabase, file_id: HirFileId) -> Hygiene {
29 Hygiene { frames: Some(HygieneFrames::new(db, file_id)) }
32 pub fn new_unhygienic() -> Hygiene {
33 Hygiene { frames: None }
36 // FIXME: this should just return name
37 pub fn name_ref_to_name(
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);
50 Either::Left(name_ref.as_name())
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;
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())
67 current = current.call_site.as_ref()?;
73 #[derive(Clone, Debug)]
74 struct HygieneFrames(Arc<HygieneFrame>);
76 #[derive(Clone, Debug, Eq, PartialEq)]
77 pub struct HygieneFrame {
78 expansion: Option<HygieneInfo>,
80 // Indicate this is a local inner macro
82 krate: Option<CrateId>,
84 call_site: Option<Arc<HygieneFrame>>,
85 def_site: Option<Arc<HygieneFrame>>,
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)))
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();
100 while let Some((mapped, origin)) =
101 current.expansion.as_ref().and_then(|it| it.map_ident_up(db, token))
103 result = current.krate;
105 let site = match origin {
106 Origin::Def => ¤t.def_site,
107 Origin::Call => ¤t.call_site,
110 let site = match site {
115 current = site.clone();
116 token = mapped.value;
123 #[derive(Debug, Clone, PartialEq, Eq)]
126 /// The start offset of the `macro_rules!` arguments or attribute input.
127 attr_input_or_mac_def_start: Option<InFile<TextSize>>,
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>,
138 db: &dyn AstDatabase,
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);
144 let loc = db.lookup_intern_macro(self.file.macro_call_id);
146 let (token_map, tt) = match &loc.kind {
147 MacroCallKind::Attr { attr_args, .. } => match self.macro_arg_shift.unshift(token_id) {
149 token_id = unshifted;
150 (&attr_args.1, self.attr_input_or_mac_def_start?)
154 InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
158 mbe::Origin::Call => (
160 InFile::new(loc.kind.file_id(), loc.kind.arg(db)?.text_range().start()),
162 mbe::Origin::Def => match (&*self.macro_def, &self.attr_input_or_mac_def_start) {
163 (TokenExpander::DeclarativeMacro { def_site_token_map, .. }, Some(tt)) => {
164 (def_site_token_map, *tt)
166 _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
171 let range = token_map.first_range_by_token(token_id, SyntaxKind::IDENT)?;
172 Some((tt.with_value(range + tt.value), origin))
176 fn make_hygiene_info(
177 db: &dyn AstDatabase,
178 macro_file: MacroFile,
180 ) -> Option<HygieneInfo> {
181 let def = loc.def.ast_id().left().and_then(|id| {
182 let def_tt = match id.to_node(db) {
183 ast::Macro::MacroRules(mac) => mac.token_tree()?,
184 ast::Macro::MacroDef(mac) => mac.body()?,
186 Some(InFile::new(id.file_id, def_tt))
188 let attr_input_or_mac_def = def.or_else(|| match loc.kind {
189 MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
190 let tt = ast_id.to_node(db).attrs().nth(invoc_attr_index as usize)?.token_tree()?;
191 Some(InFile::new(ast_id.file_id, tt))
196 let macro_def = db.macro_def(loc.def).ok()?;
197 let (_, exp_map) = db.parse_macro_expansion(macro_file).value?;
198 let macro_arg = db.macro_arg(macro_file.macro_call_id)?;
202 attr_input_or_mac_def_start: attr_input_or_mac_def
203 .map(|it| it.map(|tt| tt.syntax().text_range().start())),
204 macro_arg_shift: mbe::Shift::new(¯o_arg.0),
212 pub(crate) fn new(db: &dyn AstDatabase, file_id: HirFileId) -> HygieneFrame {
213 let (info, krate, local_inner) = match file_id.0 {
214 HirFileIdRepr::FileId(_) => (None, None, false),
215 HirFileIdRepr::MacroFile(macro_file) => {
216 let loc = db.lookup_intern_macro(macro_file.macro_call_id);
218 make_hygiene_info(db, macro_file, &loc).map(|info| (loc.kind.file_id(), info));
220 MacroDefKind::Declarative(_) => {
221 (info, Some(loc.def.krate), loc.def.local_inner)
223 MacroDefKind::BuiltIn(..) => (info, Some(loc.def.krate), false),
224 MacroDefKind::BuiltInAttr(..) => (info, None, false),
225 MacroDefKind::BuiltInDerive(..) => (info, None, false),
226 MacroDefKind::BuiltInEager(..) => (info, None, false),
227 MacroDefKind::ProcMacro(..) => (info, None, false),
232 let (calling_file, info) = match info {
234 return HygieneFrame {
245 let def_site = info.attr_input_or_mac_def_start.map(|it| db.hygiene_frame(it.file_id));
246 let call_site = Some(db.hygiene_frame(calling_file));
248 HygieneFrame { expansion: Some(info), local_inner, krate, call_site, def_site }