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) {
164 TokenExpander::MacroDef { def_site_token_map, .. }
165 | TokenExpander::MacroRules { def_site_token_map, .. },
167 ) => (def_site_token_map, *tt),
168 _ => panic!("`Origin::Def` used with non-`macro_rules!` macro"),
173 let range = token_map.first_range_by_token(token_id, SyntaxKind::IDENT)?;
174 Some((tt.with_value(range + tt.value), origin))
178 fn make_hygiene_info(
179 db: &dyn AstDatabase,
180 macro_file: MacroFile,
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()?,
188 Some(InFile::new(id.file_id, def_tt))
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))
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)?;
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(¯o_arg.0),
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);
220 make_hygiene_info(db, macro_file, &loc).map(|info| (loc.kind.file_id(), info));
222 MacroDefKind::Declarative(_) => {
223 (info, Some(loc.def.krate), loc.def.local_inner)
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),
234 let (calling_file, info) = match info {
236 return HygieneFrame {
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));
250 HygieneFrame { expansion: Some(info), local_inner, krate, call_site, def_site }