1 //! This module contains tests for macro expansion. Effectively, it covers `tt`,
2 //! `mbe`, `proc_macro_api` and `hir_expand` crates. This might seem like a
3 //! wrong architecture at the first glance, but is intentional.
5 //! Physically, macro expansion process is intertwined with name resolution. You
6 //! can not expand *just* the syntax. So, to be able to write integration tests
7 //! of the "expand this code please" form, we have to do it after name
8 //! resolution. That is, in this crate. We *could* fake some dependencies and
9 //! write unit-tests (in fact, we used to do that), but that makes tests brittle
10 //! and harder to understand.
14 mod builtin_derive_macro;
16 use std::{iter, ops::Range};
18 use base_db::{fixture::WithFixture, SourceDatabase};
19 use expect_test::Expect;
20 use hir_expand::{db::AstDatabase, InFile, MacroFile};
23 ast::{self, edit::IndentLevel},
25 SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
30 db::DefDatabase, nameres::ModuleSource, resolver::HasResolver, src::HasSource, test_db::TestDB,
35 fn check(ra_fixture: &str, mut expect: Expect) {
36 let db = TestDB::with_files(ra_fixture);
37 let krate = db.crate_graph().iter().next().unwrap();
38 let def_map = db.crate_def_map(krate);
39 let local_id = def_map.root();
40 let module = def_map.module_id(local_id);
41 let resolver = module.resolver(&db);
42 let source = def_map[local_id].definition_source(&db);
43 let source_file = match source.value {
44 ModuleSource::SourceFile(it) => it,
45 ModuleSource::Module(_) | ModuleSource::BlockExpr(_) => panic!(),
48 // What we want to do is to replace all macros (fn-like, derive, attr) with
49 // their expansions. Turns out, we don't actually store enough information
50 // to do this precisely though! Specifically, if a macro expands to nothing,
51 // it leaves zero traces in def-map, so we can't get its expansion after the
55 // <https://github.com/rust-analyzer/rust-analyzer/issues/3407>
56 // resolve/record tension!
58 // So here we try to do a resolve, which is necessary a heuristic. For macro
59 // calls, we use `as_call_id_with_errors`. For derives, we look at the impls
60 // in the module and assume that, if impls's source is a different
61 // `HirFileId`, than it came from macro expansion.
63 let mut expansions = Vec::new();
64 for macro_call in source_file.syntax().descendants().filter_map(ast::MacroCall::cast) {
65 let macro_call = InFile::new(source.file_id, ¯o_call);
67 let macro_call_id = macro_call
68 .as_call_id_with_errors(
71 |path| resolver.resolve_path_as_macro(&db, &path),
72 &mut |err| error = Some(err),
76 let macro_file = MacroFile { macro_call_id };
77 let mut expansion_result = db.parse_macro_expansion(macro_file);
78 expansion_result.err = expansion_result.err.or(error);
79 expansions.push((macro_call.value.clone(), expansion_result));
82 let mut expanded_text = source_file.to_string();
84 for (call, exp) in expansions.into_iter().rev() {
86 let mut expect_errors = false;
87 for comment in call.syntax().children_with_tokens().filter(|it| it.kind() == COMMENT) {
88 tree |= comment.to_string().contains("+tree");
89 expect_errors |= comment.to_string().contains("+errors");
92 let mut expn_text = String::new();
93 if let Some(err) = exp.err {
94 format_to!(expn_text, "/* error: {} */", err);
96 if let Some((parse, _token_map)) = exp.value {
98 assert!(!parse.errors().is_empty(), "no parse errors in expansion");
99 for e in parse.errors() {
100 format_to!(expn_text, "/* parse error: {} */\n", e);
104 parse.errors().is_empty(),
105 "parse errors in expansion: \n{:#?}",
109 let pp = pretty_print_macro_expansion(parse.syntax_node());
110 let indent = IndentLevel::from_node(call.syntax());
111 let pp = reindent(indent, pp);
112 format_to!(expn_text, "{}", pp);
115 let tree = format!("{:#?}", parse.syntax_node())
116 .split_inclusive("\n")
117 .map(|line| format!("// {}", line))
118 .collect::<String>();
119 format_to!(expn_text, "\n{}", tree)
122 let range = call.syntax().text_range();
123 let range: Range<usize> = range.into();
124 expanded_text.replace_range(range, &expn_text)
127 for impl_id in def_map[local_id].scope.impls() {
128 let src = impl_id.lookup(&db).source(&db);
129 if src.file_id.is_builtin_derive(&db).is_some() {
130 let pp = pretty_print_macro_expansion(src.value.syntax().clone());
131 format_to!(expanded_text, "\n{}", pp)
135 expect.indent(false);
136 expect.assert_eq(&expanded_text);
139 fn reindent(indent: IndentLevel, pp: String) -> String {
140 if !pp.contains('\n') {
143 let mut lines = pp.split_inclusive('\n');
144 let mut res = lines.next().unwrap().to_string();
146 if line.trim().is_empty() {
149 format_to!(res, "{}{}", indent, line)
155 fn pretty_print_macro_expansion(expn: SyntaxNode) -> String {
156 let mut res = String::new();
157 let mut prev_kind = EOF;
158 let mut indent_level = 0;
159 for token in iter::successors(expn.first_token(), |t| t.next_token()) {
160 let curr_kind = token.kind();
161 let space = match (prev_kind, curr_kind) {
162 _ if prev_kind.is_trivia() || curr_kind.is_trivia() => "",
163 (T!['{'], T!['}']) => "",
164 (T![=], _) | (_, T![=]) => " ",
166 (T![;] | T!['{'] | T!['}'], _) => "\n",
167 (_, T!['}']) => "\n",
168 (IDENT | LIFETIME_IDENT, IDENT | LIFETIME_IDENT) => " ",
169 _ if prev_kind.is_keyword() && curr_kind.is_keyword() => " ",
170 (IDENT, _) if curr_kind.is_keyword() => " ",
171 (_, IDENT) if prev_kind.is_keyword() => " ",
172 (T![>], IDENT) => " ",
173 (T![>], _) if curr_kind.is_keyword() => " ",
174 (T![->], _) | (_, T![->]) => " ",
175 (T![&&], _) | (_, T![&&]) => " ",
177 (T![:], IDENT | T!['(']) => " ",
178 (T![:], _) if curr_kind.is_keyword() => " ",
179 (T![fn], T!['(']) => "",
180 (T![']'], _) if curr_kind.is_keyword() => " ",
181 (T![']'], T![#]) => "\n",
182 _ if prev_kind.is_keyword() => " ",
187 T!['{'] => indent_level += 1,
188 T!['}'] => indent_level -= 1,
194 let level = if curr_kind == T!['}'] { indent_level - 1 } else { indent_level };
195 res.push_str(&" ".repeat(level));
197 prev_kind = curr_kind;
198 format_to!(res, "{}", token)