Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//! Macro expansion utilities.

use std::mem;

use base_db::Crate;
use cfg::CfgOptions;
use drop_bomb::DropBomb;
use hir_expand::AstId;
use hir_expand::span_map::SpanMapRef;
use hir_expand::{
    ExpandError, ExpandErrorKind, ExpandResult, HirFileId, InFile, Lookup, MacroCallId,
    eager::EagerCallBackFn, mod_path::ModPath, span_map::SpanMap,
};
use span::{AstIdMap, SyntaxContext};
use syntax::ast::HasAttrs;
use syntax::{AstNode, Parse, ast};
use triomphe::Arc;
use tt::TextRange;

use crate::{
    MacroId, UnresolvedMacro, attrs::AttrFlags, db::DefDatabase, expr_store::HygieneId,
    macro_call_as_call_id, nameres::DefMap,
};

#[derive(Debug)]
pub(super) struct Expander {
    span_map: SpanMap,
    current_file_id: HirFileId,
    ast_id_map: Arc<AstIdMap>,
    /// `recursion_depth == usize::MAX` indicates that the recursion limit has been reached.
    recursion_depth: u32,
    recursion_limit: usize,
}

impl Expander {
    pub(super) fn new(
        db: &dyn DefDatabase,
        current_file_id: HirFileId,
        def_map: &DefMap,
    ) -> Expander {
        let recursion_limit = def_map.recursion_limit() as usize;
        let recursion_limit = if cfg!(test) {
            // Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
            std::cmp::min(32, recursion_limit)
        } else {
            recursion_limit
        };
        Expander {
            current_file_id,
            recursion_depth: 0,
            recursion_limit,
            span_map: db.span_map(current_file_id),
            ast_id_map: db.ast_id_map(current_file_id),
        }
    }

    pub(super) fn ctx_for_range(&self, range: TextRange) -> SyntaxContext {
        self.span_map.span_for_range(range).ctx
    }

    pub(super) fn hygiene_for_range(&self, db: &dyn DefDatabase, range: TextRange) -> HygieneId {
        match self.span_map.as_ref() {
            hir_expand::span_map::SpanMapRef::ExpansionSpanMap(span_map) => {
                HygieneId::new(span_map.span_at(range.start()).ctx.opaque_and_semiopaque(db))
            }
            hir_expand::span_map::SpanMapRef::RealSpanMap(_) => HygieneId::ROOT,
        }
    }

    pub(super) fn is_cfg_enabled(
        &self,
        owner: &dyn HasAttrs,
        cfg_options: &CfgOptions,
    ) -> Result<(), cfg::CfgExpr> {
        AttrFlags::is_cfg_enabled_for(owner, cfg_options)
    }

    pub(super) fn enter_expand<T: ast::AstNode>(
        &mut self,
        db: &dyn DefDatabase,
        macro_call: ast::MacroCall,
        krate: Crate,
        resolver: impl Fn(&ModPath) -> Option<MacroId>,
        eager_callback: EagerCallBackFn<'_>,
    ) -> Result<ExpandResult<Option<(Mark, Option<Parse<T>>)>>, UnresolvedMacro> {
        // FIXME: within_limit should support this, instead of us having to extract the error
        let mut unresolved_macro_err = None;

        let result = self.within_limit(db, |this| {
            let macro_call = this.in_file(&macro_call);

            let expands_to = hir_expand::ExpandTo::from_call_site(macro_call.value);
            let ast_id = AstId::new(macro_call.file_id, this.ast_id_map().ast_id(macro_call.value));
            let path = macro_call.value.path().and_then(|path| {
                let range = path.syntax().text_range();
                let mod_path = ModPath::from_src(db, path, &mut |range| {
                    this.span_map.span_for_range(range).ctx
                })?;
                let call_site = this.span_map.span_for_range(range);
                Some((call_site, mod_path))
            });

            let Some((call_site, path)) = path else {
                return ExpandResult::only_err(ExpandError::other(
                    this.span_map.span_for_range(macro_call.value.syntax().text_range()),
                    "malformed macro invocation",
                ));
            };

            match macro_call_as_call_id(
                db,
                ast_id,
                &path,
                call_site.ctx,
                expands_to,
                krate,
                |path| resolver(path).map(|it| db.macro_def(it)),
                eager_callback,
            ) {
                Ok(call_id) => call_id,
                Err(resolve_err) => {
                    unresolved_macro_err = Some(resolve_err);
                    ExpandResult { value: None, err: None }
                }
            }
        });

        if let Some(err) = unresolved_macro_err { Err(err) } else { Ok(result) }
    }

    pub(super) fn enter_expand_id<T: ast::AstNode>(
        &mut self,
        db: &dyn DefDatabase,
        call_id: MacroCallId,
    ) -> ExpandResult<Option<(Mark, Option<Parse<T>>)>> {
        self.within_limit(db, |_this| ExpandResult::ok(Some(call_id)))
    }

    pub(super) fn exit(&mut self, Mark { file_id, span_map, ast_id_map, mut bomb }: Mark) {
        self.span_map = span_map;
        self.current_file_id = file_id;
        self.ast_id_map = ast_id_map;
        if self.recursion_depth == u32::MAX {
            // Recursion limit has been reached somewhere in the macro expansion tree. Reset the
            // depth only when we get out of the tree.
            if !self.current_file_id.is_macro() {
                self.recursion_depth = 0;
            }
        } else {
            self.recursion_depth -= 1;
        }
        bomb.defuse();
    }

    pub(super) fn in_file<T>(&self, value: T) -> InFile<T> {
        InFile { file_id: self.current_file_id, value }
    }

    pub(super) fn current_file_id(&self) -> HirFileId {
        self.current_file_id
    }

    fn within_limit<F, T: ast::AstNode>(
        &mut self,
        db: &dyn DefDatabase,
        op: F,
    ) -> ExpandResult<Option<(Mark, Option<Parse<T>>)>>
    where
        F: FnOnce(&mut Self) -> ExpandResult<Option<MacroCallId>>,
    {
        if self.recursion_depth == u32::MAX {
            // Recursion limit has been reached somewhere in the macro expansion tree. We should
            // stop expanding other macro calls in this tree, or else this may result in
            // exponential number of macro expansions, leading to a hang.
            //
            // The overflow error should have been reported when it occurred (see the next branch),
            // so don't return overflow error here to avoid diagnostics duplication.
            cov_mark::hit!(overflow_but_not_me);
            return ExpandResult::ok(None);
        }

        let ExpandResult { value, err } = op(self);
        let Some(call_id) = value else {
            return ExpandResult { value: None, err };
        };
        if self.recursion_depth as usize > self.recursion_limit {
            self.recursion_depth = u32::MAX;
            cov_mark::hit!(your_stack_belongs_to_me);
            return ExpandResult::only_err(ExpandError::new(
                db.macro_arg_considering_derives(call_id, &call_id.lookup(db).kind).2,
                ExpandErrorKind::RecursionOverflow,
            ));
        }

        let res = db.parse_macro_expansion(call_id);

        let err = err.or(res.err);
        ExpandResult {
            value: {
                let parse = res.value.0.cast::<T>();

                self.recursion_depth += 1;
                let old_file_id = std::mem::replace(&mut self.current_file_id, call_id.into());
                let old_span_map =
                    std::mem::replace(&mut self.span_map, db.span_map(self.current_file_id));
                let prev_ast_id_map =
                    mem::replace(&mut self.ast_id_map, db.ast_id_map(self.current_file_id));
                let mark = Mark {
                    file_id: old_file_id,
                    span_map: old_span_map,
                    ast_id_map: prev_ast_id_map,
                    bomb: DropBomb::new("expansion mark dropped"),
                };
                Some((mark, parse))
            },
            err,
        }
    }

    #[inline]
    pub(super) fn ast_id_map(&self) -> &AstIdMap {
        &self.ast_id_map
    }

    #[inline]
    pub(super) fn span_map(&self) -> SpanMapRef<'_> {
        self.span_map.as_ref()
    }
}

#[derive(Debug)]
pub(super) struct Mark {
    file_id: HirFileId,
    span_map: SpanMap,
    ast_id_map: Arc<AstIdMap>,
    bomb: DropBomb,
}