Skip to main content

hir_expand/
declarative.rs

1//! Compiled declarative macro expanders (`macro_rules!` and `macro`)
2
3use std::{cell::Cell, ops::ControlFlow};
4
5use base_db::{Crate, SourceDatabase};
6use span::{Edition, Span, SyntaxContext};
7use stdx::TupleExt;
8use syntax::{
9    AstNode,
10    ast::{self, HasAttrs},
11};
12use syntax_bridge::DocCommentDesugarMode;
13
14use crate::{
15    AstId, ExpandError, ExpandErrorKind, ExpandResult, HirFileId, Lookup, MacroCallId,
16    MacroCallStyle,
17    attrs::{AstKeyValueMetaExt, AstPathExt, expand_cfg_attr},
18    hygiene::{Transparency, apply_mark},
19    tt,
20};
21
22/// Old-style `macro_rules` or the new macros 2.0
23#[derive(Debug, Clone, Eq, PartialEq)]
24pub struct DeclarativeMacroExpander {
25    pub mac: mbe::DeclarativeMacro,
26    pub transparency: Transparency,
27    edition: Edition,
28}
29
30impl DeclarativeMacroExpander {
31    pub fn expand(
32        &self,
33        db: &dyn SourceDatabase,
34        tt: &tt::TopSubtree,
35        call_id: MacroCallId,
36        span: Span,
37    ) -> ExpandResult<(tt::TopSubtree, Option<u32>)> {
38        let loc = call_id.loc(db);
39        let last_mark = Cell::new(None);
40        match self.mac.err() {
41            Some(_) => ExpandResult::new(
42                (tt::TopSubtree::empty(tt::DelimSpan { open: span, close: span }), None),
43                ExpandError::new(span, ExpandErrorKind::MacroDefinition),
44            ),
45            None => self
46                .mac
47                .expand(
48                    db,
49                    tt,
50                    |s| {
51                        // `apply_mark` is relatively expensive, and most macros only have one
52                        // context. Caching the result avoids doing extra work.
53                        s.ctx = match last_mark.get() {
54                            Some((ctx, marked)) if ctx == s.ctx => marked,
55                            _ => {
56                                let marked = apply_mark(
57                                    db,
58                                    s.ctx,
59                                    call_id.into(),
60                                    self.transparency,
61                                    self.edition,
62                                );
63                                last_mark.set(Some((s.ctx, marked)));
64                                marked
65                            }
66                        };
67                    },
68                    loc.kind.call_style(),
69                    span,
70                )
71                .map_err(Into::into),
72        }
73    }
74
75    pub fn expand_unhygienic(
76        &self,
77        db: &dyn SourceDatabase,
78        tt: &tt::TopSubtree,
79        call_style: MacroCallStyle,
80        call_site: Span,
81    ) -> ExpandResult<tt::TopSubtree> {
82        match self.mac.err() {
83            Some(_) => ExpandResult::new(
84                tt::TopSubtree::empty(tt::DelimSpan { open: call_site, close: call_site }),
85                ExpandError::new(call_site, ExpandErrorKind::MacroDefinition),
86            ),
87            None => self
88                .mac
89                .expand(db, tt, |_| (), call_style, call_site)
90                .map(TupleExt::head)
91                .map_err(Into::into),
92        }
93    }
94}
95
96#[salsa::tracked]
97impl AstId<ast::Macro> {
98    /// Fetches (and compiles) the expander of this decl macro.
99    #[salsa::tracked(returns(ref))]
100    pub fn decl_macro_expander(
101        self,
102        db: &dyn SourceDatabase,
103        def_crate: Crate,
104    ) -> DeclarativeMacroExpander {
105        let id = self;
106        let (root, map) = id.file_id.parse_with_map(db);
107
108        let root = root.syntax_node();
109
110        let transparency = |node: ast::AnyHasAttrs| {
111            let mut cfg_options = None;
112            expand_cfg_attr(
113                node.attrs(),
114                || cfg_options.get_or_insert_with(|| def_crate.cfg_options(db)),
115                |attr, _| {
116                    if let ast::Meta::KeyValueMeta(attr) = attr
117                        && attr.path().is1("rustc_macro_transparency")
118                        && let Some(value) = attr.value_string()
119                    {
120                        match &*value {
121                            "transparent" => ControlFlow::Break(Transparency::Transparent),
122                            // "semitransparent" is for old rustc versions.
123                            "semiopaque" | "semitransparent" => {
124                                ControlFlow::Break(Transparency::SemiOpaque)
125                            }
126                            "opaque" => ControlFlow::Break(Transparency::Opaque),
127                            _ => ControlFlow::Continue(()),
128                        }
129                    } else {
130                        ControlFlow::Continue(())
131                    }
132                },
133            )
134        };
135        let ctx_edition = |ctx: SyntaxContext| {
136            if ctx.is_root() {
137                def_crate.data(db).edition
138            } else {
139                // UNWRAP-SAFETY: Only the root context has no outer expansion
140                let krate = crate::MacroCallId::from(ctx.outer_expn(db).unwrap()).loc(db).def.krate;
141                krate.data(db).edition
142            }
143        };
144        let (mac, transparency) = match id.to_ptr(db).to_node(&root) {
145            ast::Macro::MacroRules(macro_rules) => (
146                match macro_rules.token_tree() {
147                    Some(arg) => {
148                        let tt = syntax_bridge::syntax_node_to_token_tree(
149                            arg.syntax(),
150                            map,
151                            map.span_for_range(
152                                macro_rules.macro_rules_token().unwrap().text_range(),
153                            ),
154                            DocCommentDesugarMode::Mbe,
155                        );
156
157                        mbe::DeclarativeMacro::parse_macro_rules(&tt, ctx_edition)
158                    }
159                    None => mbe::DeclarativeMacro::from_err(mbe::ParseError::Expected(
160                        "expected a token tree".into(),
161                    )),
162                },
163                transparency(ast::AnyHasAttrs::from(macro_rules))
164                    .unwrap_or(Transparency::SemiOpaque),
165            ),
166            ast::Macro::MacroDef(macro_def) => (
167                match macro_def.body() {
168                    Some(body) => {
169                        let span =
170                            map.span_for_range(macro_def.macro_token().unwrap().text_range());
171                        let args = macro_def.args().map(|args| {
172                            syntax_bridge::syntax_node_to_token_tree(
173                                args.syntax(),
174                                map,
175                                span,
176                                DocCommentDesugarMode::Mbe,
177                            )
178                        });
179                        let body = syntax_bridge::syntax_node_to_token_tree(
180                            body.syntax(),
181                            map,
182                            span,
183                            DocCommentDesugarMode::Mbe,
184                        );
185
186                        mbe::DeclarativeMacro::parse_macro2(args.as_ref(), &body, ctx_edition)
187                    }
188                    None => mbe::DeclarativeMacro::from_err(mbe::ParseError::Expected(
189                        "expected a token tree".into(),
190                    )),
191                },
192                transparency(macro_def.into()).unwrap_or(Transparency::Opaque),
193            ),
194        };
195        let edition = ctx_edition(match id.file_id {
196            HirFileId::MacroFile(macro_file) => macro_file.lookup(db).ctxt,
197            HirFileId::FileId(file) => SyntaxContext::root(file.edition(db)),
198        });
199        DeclarativeMacroExpander { mac, transparency, edition }
200    }
201}